An if
-statement tests a variable in some way. In Go we can build complex if constructs with else
-if and else parts. Statements are evaluated until a condition is true.
With initialization statements, we can declare variables in the same line as an if
-statement. This syntax leads to clean, understandable code.
We see an if
-statement with else
-if and else parts. The variable named "value" is initialized to 5. The first if
-statement test evaluates to true.
if
-statement has no surrounding parentheses. The body statements are surrounded by curly braces.package main
import "fmt"
func main() {
value := 10
// Test the value with an if-else construct.
if value >= 5 {
fmt.Println(5)
} else if value >= 15 {
fmt.Println(15) // Not reached.
} else {
fmt.Println("?") // Not reached.
}
}5
A variable can be declared and initialized before the condition of an if
-statement (on the same line). This syntax makes sense.
if
-statement and its contents. Here we cannot reference "t" outside the if.package main import "fmt" func test() int { return 100 } func main() { // Initialize a variable in an if-statement. // ... Then check it against a constant. if t := test(); t == 100 { fmt.Println(t) } }100
The if
-statement in Go is often used when testing a map. We assign 2 values to a map lookup expression, and then test the boolean "exists" value.
package main
import "fmt"
func main() {
test := map[string]bool{}
test["bird"] = true
// We can assign to a map, then test the bool ok in a single if-statement.
if value, ok := test["bird"]; ok {
fmt.Println("Value:", value)
}
}Value: true
When we declare a variable at the start of an if
-statement, it is scoped to that if
-statement (and any else
-if and elses).
package main
import "fmt"
func main() {
mult := 10
// The variable "t" can be accessed only in the if-statement.
if t := 100 * mult; t >= 200 {
fmt.Println(t)
}
// This causes an error.
fmt.Println(t)
}C:\programs\file.go:16: undefined: t
An "else" in a Go program must be preceded by the closing brace. We cannot put "else" on a separate line. A compile-time error will occur.
package main
import "fmt"
func main() {
// This program won't compile.
value := 10
if value == 20 {
fmt.Println(20)
}
else {
fmt.Println(0)
}
}# command-line-arguments
syntax error: unexpected semicolon or newline before else
syntax error: unexpected }
switch
performanceIn a Go benchmark we can show an integer switch
has better performance from an integer if-else
chain. This must be carefully tested.
switch
or if statements. Some initialization is needed.Ifs are powerful in Go. In most ways they are the same as those in C-like languages. But the initialization statement feature provides a new, scoped variable for the block.