Go if else


if指定的条件为 trueif语句执行语句。如果条件为false ,则可以使用else语句执行另一个语句。

注意: else语句是可选的。

x := 7
  if x%2 == 0 {
    // This statement is executed if x is even
  } else {
    // This statement is executed if x is odd
  }

可以嵌套多个if...else语句来创建else if子句。

x := 7
  if x == 2 {
    // this statement is executed if x is 2
  } else if x == 4 {
    // this statement is executed if x is 4
  } else if x == 7 {
    // this statement is executed if x is 7
  } else {
    // this statement is executed if none of the aboves is true
  }

在Go中,您可以在if条件之前加上语句。然后,包含的变量定义对完整的if块有效。

if x := 3; x == 2 {
    // this statement is executed if x is 2
  } else if x == 3 {
    // this statement is executed if x is 3
  } else {
    // this statement is executed if none of the aboves is true
  }

更多go教程

学习更多go教程