if statement
suggest changeA simple if
statement:
func returnValues(ok bool) (int, bool) {
return 5, ok
}
func main() {
a := 5
b := 5
if a == b {
fmt.Print("a is equal to b\n")
} else {
fmt.Print("a is not equal to b\n")
}
if n, ok := returnValues(true); ok {
fmt.Printf("ok is true, n: %d\n", n)
} else {
fmt.Printf("ok is false, n: %d\n", n)
}
}
a is equal to b
ok is true, n: 5
A variable declared in if
statement is scoped to that statement. This example fails to compile because of that:
func returnValues(ok bool) (int, bool) {
return 5, ok
}
func main() {
if n, ok := returnValues(true); ok {
fmt.Print("ok is true, n: %d\n", n)
} else {
fmt.Print("ok is false, n: %d\n", n)
}
// n is only visible within if statement, so this fails compilation
fmt.Printf("n: %d\n", n)
}
# test
./main.go:19:24: undefined: n
exit status 2
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents