Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go if/else语句实例
Go if/else语句实例
作者:--    发布时间:2019-11-20

在go语言中的分支,ifelse是直接的。

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html

这里有一个基本的例子。
一个if语句可以不用else语句。
语句可以在条件语句之前; 在此语句中声明的任何变量在所有分支中都可用。
注意,go语言中的条件不需要围绕括号,但是大括号是必需的。

go语言中没有三元组,所以即使对于基本条件,也需要使用一个完整的if语句。

if-else.go的完整代码如下所示 -

package main

import "fmt"

func main() {

    // here's a basic example.
    if 7%2 == 0 {
        fmt.println("7 is even")
    } else {
        fmt.println("7 is odd")
    }

    // you can have an `if` statement without an else.
    if 8%4 == 0 {
        fmt.println("8 is divisible by 4")
    }

    // a statement can precede conditionals; any variables
    // declared in this statement are available in all
    // branches.
    if num := 9; num < 0 {
        fmt.println(num, "is negative")
    } else if num < 10 {
        fmt.println(num, "has 1 digit")
    } else {
        fmt.println(num, "has multiple digits")
    }
}

// note that you don't need parentheses around conditions
// in go, but that the braces are required.

执行上面代码,将得到以下输出结果 -

f:\worksp\golang>go run if-else.go
7 is odd
8 is divisible by 4
9 has 1 digit

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册