From b70e1e7f7cb52e8915219f846e2d0334b3280845 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sat, 13 Oct 2012 09:17:44 -0700 Subject: [PATCH] publish if/else --- examples.txt | 2 +- examples/if-else/if-else.go | 36 ++++++++++++++++++++++++------------ examples/if-else/if-else.sh | 8 +++++++- 3 files changed, 32 insertions(+), 14 deletions(-) diff --git a/examples.txt b/examples.txt index 2e12d91..878ca2f 100644 --- a/examples.txt +++ b/examples.txt @@ -4,7 +4,7 @@ Hello World # Short Declarations # Constants # For -# If/Else +If/Else # Switch Arrays Slices diff --git a/examples/if-else/if-else.go b/examples/if-else/if-else.go index f843ed6..563474f 100644 --- a/examples/if-else/if-else.go +++ b/examples/if-else/if-else.go @@ -1,23 +1,35 @@ -// If/else in Go is straight-forward. +// Branching with `if` and `else` in Go is +// straight-forward. package main import "fmt" func main() { - // If/else is straight-forward. Note that there are no - // enclosing parentheses around the condition. - // Also, there is no ternary operator (`?`) in Go. - fmt.Print("7 is ") + + // Here's a basic example. if 7%2 == 0 { - fmt.Println("even") - } else if 7%2 == 1 { - fmt.Println("odd") + fmt.Println("7 is even") } else { - fmt.Println("???") + fmt.Println("7 is odd") + } + + // You can have an `if` statement without an else. + if 8%4 == 0 { + fmt.Println("8 is divisible by 4") + } + + // A statement can proceed conditionals; any variables + // declared in this statement are available in all + // branches. + if num := 9; num < 0 { + fmt.Println(num, "is negative") + } else if num < 10 { + fmt.Println(num, "has 1 digit") + } else { + fmt.Println(num, "has multiple digits") } } -// There is no ternary operator (i.e. `?`) in Go, so -// you'll need to use a full if/else even for very basic -// conditions. +// Note that you don't need parenthesis around conditions +// in Go, but that the brackets are required. diff --git a/examples/if-else/if-else.sh b/examples/if-else/if-else.sh index 917105f..84d97f2 100644 --- a/examples/if-else/if-else.sh +++ b/examples/if-else/if-else.sh @@ -1,2 +1,8 @@ -$ go run if-else.go +$ go run if-else.go 7 is odd +8 is divisible by 4 +9 has 1 digit + +# There is no [ternary if](http://en.wikipedia.org/wiki/%3F:) +# in Go, so you'll need to use a full if statement even +# for basic conditions.