if语句

一个简单的if语句例子:
Go
Output
package main
import "fmt"
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
Program exited.
👉
点击此处
👈
亲自在编程操场执行上述代码。
if语句中声明的变量作用域仅为if语句内部。下面的例子会编译失败:
Go
Output
package main
import "fmt"
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只在if语句内可见,所以这会在编译时报错
fmt.Printf("n: %d\n", n)
}
./prog.go:17:24: undefined: n
Go build failed.
👉
点击此处
👈
亲自在编程操场执行上述代码。