if语句
一个简单的if
语句例子:
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
语句内部。下面的例子会编译失败:
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.
最后更新于
这有帮助吗?