导航
×
   ❮   
HTML CSS JavaScript PHP Go ECMS

Go else 语句


else 语句

使用 else 语句指定一个代码块,如果条件为 false 则执行。

语法

if condition {
  // 如果 condition 为 true,则执行的代码
} else {
  // 如果 condition 为 false,则执行的代码
}

使用 if else 语句

实例

在此实例中,时间 (20) 大于 18,因此 if 条件为 false。因此,我们继续执行 else 条件,并在屏幕上打印“晚上好”。如果时间小于 18,程序将打印“白天好”。

package main
import ("fmt")

func main() {
  time := 20
  if (time< 18) {
    fmt.Println("白天好。")
  } else {
    fmt.Println("晚上好。")
  }
}
亲自试一试 »

实例

在此实例中,温度为 14,因此 if 的条件为 false,因此执行 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 }
亲自试一试 »

freew3c.com 中文网是独立运营的中文开发者学习平台,与 freew3c.com 无关联。提供的内容仅用于学习和测试,不保证内容的正确性。


Copyright @2020-2026 京ICP备888888号-8