美文网首页
Golang学习笔记-1.7 if-else语句

Golang学习笔记-1.7 if-else语句

作者: xunk1900 | 来源:发表于2018-07-12 23:34 被阅读0次

本文系第七篇Golang语言学习教程

if-else

if 是条件语句
语法如下:

if condition {  
}

如果condition为真,则执行{}之间的代码

Go还有可选的else ifelse语句

if condition {
} else if condition {
} else {
}

else if语句可以有任意数量,从上到下判断。
如果if 或else if判断为真,则执行相应的{}中代码。
如果没有条件为真,则自动执行else代码

先写一个简单的判断数字是奇数偶数的程序:

package main

import "fmt"

func main(){
    num := 21
    if num % 2 == 0 { //如果 num 取 2 的余数为 0
        fmt.Println("this number is env")  //输出this number is env
    } else {
        fmt.Println("this number is odd")  //若余数不为 0 ,则输出this number is env
    }
}

if num % 2 == 0用来检测num 取 2 的余数是否为 0 。
以上程序输出:num 取 2 的余数为 0

if 还有另外一种形式,它包含一个statement可选部分,该条件在条件判断前运行。
语法如下:

if statement; condition {  
}

重写判断奇偶数的程序:

package main

import "fmt"

func main(){
    if numb := 21; numb % 2 == 0 {
        fmt.Println("this number is env")
    } else {
        fmt.Println("this number is odd")
    }
}

以上程序中,if是在条件中赋值,所以条件中赋值的变量numb作用域只能在这个if代码块中。 如果试图从外部的ifelse 中访问numb,编译器不会通过。

注意:

else 一定要在 if 语句 } 之后,否则会报错

条件语句还有switch语句,下一节将学习switch语句。

以上为学习Golang if-else篇

相关文章

网友评论

      本文标题:Golang学习笔记-1.7 if-else语句

      本文链接:https://www.haomeiwen.com/subject/enuhpftx.html