Golang初级系列教程-控制结构-ifelse

程序能够根据不同的条件执行不同的功能——如果你想去海滩请向左转,如果想去电影院请向右转。if else语句是非常简单的控制结构。在Go中通常的用法如下。

if some_boolean_expression {
    // execute this block if some_boolean_expression is true
} else if alternate_boolean_expression {
    // execute this block if alternate_boolean_expression is true
} else {
    // if none of the other blocks are executed, then execute this block
}

几点提示:

  • some_boolean_expressionalternate_boolean_expression 需要为bool类型的值: true 或者 false
  • 在判定语句两侧不需要()——也可以使用,但是没必要
  • Go独特之处:需要将大括号{if else放在同一行,否则会报错哦。missing condition in if statement or syntax error: unexpected semicolon or newline before else.
  • 如果多个判定都为true,那么总是会执行遇到的第一个为正确的语句块

注意:int类型不能作为真值使用——和C语言不同,在C语言中整型和指针都可以作为真值使用

必须具有明确的值 ture 或者 false, 或者使用能够产生 true 或者 false 的表达式。以下能够获得真值的表达式是允许的。


== equal to
!= not equal to
< less than
<= less than or equal to
> greater than
<= greater than or equal to
&& and
|| or

通过几个实例说明上述的内容。首先,使用bool值。

package main

import "fmt"

func main() {
    if true {
        fmt.Println("the true block is executed")
    }

    if false {
        fmt.Println("the false block won't be executed")
    }
}
the true block is executed

通过比较操作符获取真值

package main

import "fmt"

func main() {
    a, b := 4, 5
    if a < b {
        fmt.Println("a is less than b")
    } else if a > b {
        fmt.Println("a is greater than b")
    } else {
        fmt.Println("a is equal to b")
    }
}
a is less than b

if else非常的简单,不需要再过多的举例了。以下让我们简单列举一些常见的错误即可。

错误小片段

//error: non-bool 5 (type ideal) used as if condition
if 5 {  //an integer type does not evaluate to a bool by itself
}

//error: non-bool s (type string) used as if condition
var s string
if s { //a string type does not evaluate to a bool by itself
}

//error: non-bool e (type os.Error) used as if condition
var e os.Error
e = nil
if e { //nil value is not a true or false
}

//error: missing condition in if statement
if true  //the open brace needs to be on this line
{ }

//error: unexpected semicolon or newline before else
if true {
} // the else needs to be on this line itself
else {
}

Golang一种神奇的语言,让我们一起进步