Go if else 语句

else 语句

使用 else 语句来指定条件为假时要执行的代码块。

语法

if 条件 {  
  // 条件为真时要执行的代码  
} else {  
  // 条件为假时要执行的代码  
}

使用 if else 语句

实例

在这个例子中,时间(20)大于 18,所以 if 条件为假。因此,我们继续执行 else 条件,并在屏幕上打印“晚上好”。如果时间小于 18,程序将打印“日安”:

package main  
import ("fmt")  
  
func main() {  
  time := 20  
  if (time < 18) {  
    fmt.Println("日安。")  
  } else {  
    fmt.Println("晚安。")  
  }  
}

亲自试一试

实例

在这个例子中,温度为 14,所以 if 的条件为假,因此执行 else 语句中的代码行:

package main  
import ("fmt")  
  
func main() {  
  temperature := 14  
  if (temperature > 15) {  
    fmt.Println("外面很暖和。")  
  } else {  
    fmt.Println("外面很冷。")  
  }  
}

亲自试一试

else 语句中的括号应该是这样的 } else {

实例

else 括号放在不同的行中会引发错误:

package main  
import ("fmt")  
  
func main() {  
  temperature := 14  
  if (temperature > 15) {  
    fmt.Println("外面很暖和。")  
  } // 这会引发错误  
  else {  
    fmt.Println("外面很冷。")  
  }  
}

结果:

./prog.go:9:3: syntax error: unexpected else, expecting }

亲自试一试