publish if/else
This commit is contained in:
parent
08345afa06
commit
b70e1e7f7c
@ -4,7 +4,7 @@ Hello World
|
|||||||
# Short Declarations
|
# Short Declarations
|
||||||
# Constants
|
# Constants
|
||||||
# For
|
# For
|
||||||
# If/Else
|
If/Else
|
||||||
# Switch
|
# Switch
|
||||||
Arrays
|
Arrays
|
||||||
Slices
|
Slices
|
||||||
|
@ -1,23 +1,35 @@
|
|||||||
// If/else in Go is straight-forward.
|
// Branching with `if` and `else` in Go is
|
||||||
|
// straight-forward.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// If/else is straight-forward. Note that there are no
|
|
||||||
// enclosing parentheses around the condition.
|
// Here's a basic example.
|
||||||
// Also, there is no ternary operator (`?`) in Go.
|
|
||||||
fmt.Print("7 is ")
|
|
||||||
if 7%2 == 0 {
|
if 7%2 == 0 {
|
||||||
fmt.Println("even")
|
fmt.Println("7 is even")
|
||||||
} else if 7%2 == 1 {
|
|
||||||
fmt.Println("odd")
|
|
||||||
} else {
|
} 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
|
// Note that you don't need parenthesis around conditions
|
||||||
// you'll need to use a full if/else even for very basic
|
// in Go, but that the brackets are required.
|
||||||
// conditions.
|
|
||||||
|
@ -1,2 +1,8 @@
|
|||||||
$ go run if-else.go
|
$ go run if-else.go
|
||||||
7 is odd
|
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.
|
||||||
|
Loading…
x
Reference in New Issue
Block a user