[译] part 8: golang if else 语句

if是条件语句,语法为,golang

if condition {  
}
复制代码

若是conditiontrue,介于{}之间的代码块将被执行。c#

与 C 之类的其余语言不一样,即便{}之间只有一个语句,{}也是强制性须要的。less

else ifelse对于if来讲是可选的。spa

if condition {  
} else if condition {
} else {
}
复制代码

if else的数量不受限制,它们从上到下判断条件是否为真。若是if else或者if的条件为true,则执行相应的代码块。若是没有条件为真,则执行else的代码块。code

让咱们写一个简单的程序来查找数字是奇数仍是偶数。get

package main

import (  
    "fmt"
)

func main() {  
    num := 10
    if num % 2 == 0 { //checks if number is even
        fmt.Println("the number is even") 
    }  else {
        fmt.Println("the number is odd")
    }
}
复制代码

Run in playground编译器

if num % 2 == 0语句检查将数字除以 2 的结果是否为零。若是是,则打印"the number is even",不然打印"the number is odd"。在上面的程序中,将打印the number is evenstring

if变量还能够包含一个可选的statement,它在条件判断以前执行。语法为it

if statement; condition {  
}
复制代码

让咱们使用上面的语法重写程序,判断数字是偶数仍是奇数。io

package main

import (  
    "fmt"
)

func main() {  
    if num := 10; num % 2 == 0 { //checks if number is even
        fmt.Println(num,"is even") 
    }  else {
        fmt.Println(num,"is odd")
    }
}
复制代码

Run in playground

在上面的程序中,numif语句中初始化。须要注意的一点是,num仅可从ifelse内部访问。即num的范围仅限于if else代码块,若是咱们尝试从ifelse外部访问num,编译器会报错。

让咱们再写一个使用else if的程序。

package main

import (  
    "fmt"
)

func main() {  
    num := 99
    if num <= 50 {
        fmt.Println("number is less than or equal to 50")
    } else if num >= 51 && num <= 100 {
        fmt.Println("number is between 51 and 100")
    } else {
        fmt.Println("number is greater than 100")
    }

}
复制代码

在上面的程序中,若是else if num >= 51 && num <= 100为真,那么程序将输出number is between 51 and 100

注意事项

else语句应该在if语句结束的}以后的同一行开始。若是不是,编译器会报错。

让咱们经过一个程序来理解这一点。

package main

import (  
    "fmt"
)

func main() {  
    num := 10
    if num % 2 == 0 { //checks if number is even
        fmt.Println("the number is even") 
    }  
    else {
        fmt.Println("the number is odd")
    }
}
复制代码

Run in playground

在上面的程序中,else语句没有在if语句接近}以后的同一行开始。相反,它从下一行开始。 Go 中不容许这样作,若是运行此程序,编译器将输出错误,

main.go:12:5: syntax error: unexpected else, expecting }  
复制代码

缘由是 Go 是自动插入分号的。你能够从这个连接查看有关分号插入规则的信息https://golang.org/ref/spec#Semicolons。

在规则中,若是}是该行最后的一个标记,go 将会在以后插入分号。所以,在if语句的}以后会自动插入分号。

因此咱们的程序实际是下面这样的,

if num%2 == 0 {  
      fmt.Println("the number is even") 
};  //semicolon inserted by Go
else {  
      fmt.Println("the number is odd")
}
复制代码

由于{...} else {...}是一个语句,因此在它的中间不该该有分号。所以,须要将else放在`}后的同一行中。

我已经经过在if语句的}以后插入else来重写程序,以防止自动分号插入。

package main

import (  
    "fmt"
)

func main() {  
    if num := 10; num % 2 == 0 { //checks if number is even
        fmt.Println("the number is even") 
    } else {
        fmt.Println("the number is odd")
    }
}
复制代码

Run in playground

如今编译器能够正常执行了。

相关文章
相关标签/搜索