2.4 循环和条件

peter
• 阅读 1028

循环

与其他主要编程语言的差异

Go 语言仅支持循环关键字 for

for j := 7; j <= 9; j++

// while 条件循环
// while (n < 5)
n := 0
for n < 5 {
  n++
  fmt.Println(n)
}

// 无限循环
// while (true)
n := 0
for {
  ...
}

测试实例 1

package loop_test

import "testing"

func TestWhileLoop (t *testing.T) {
    n := 0
    for n < 5 {
        t.Log(n)
        n++
    }
    // 输出:0 1 2 3 4
    // 每个输出都会换行,为了表示方便,把输出写在一行
}

if 条件

与其他主要编程语言的差异

  1. condition 表达式结果必须为布尔值

  2. 支持变量赋值:

    if var declaration; condition {
      // code to be expected if condition is true
    }

    为什么需要这样的一种特性呢?

    因为 Go 语言的函数是支持多返回值的,一个方法可以同时返回两个值,我们可以对其返回的值进行判断,如代码实例 2 中所示。

测试实例 2

func TestIfMultiSec(t *testing.T) {
    if v, err := someFun(); err==nil {
        t.Log("没有错误")
        ...
    } else {
        t.Log("有错误")
        ...
    }
}

switch 条件

与其他主要编程语言的差异

  1. 条件表达式不限制为常量或者整数;
  2. 单个 case 中,可以出现多个结果选项,使用逗号分割;
  3. 与 C 语言等规则相反,Go 语言不需要用 break 来明确退出一个 case
  4. 可以不设定 switch 之后的条件表达式,在此种情况下,整个 switch 结构与多个 if...else... 的逻辑作用等同;

测试实例 3

func TestSwitchMultiCase(t *testing.T) {
    for i := 0; i < 5; i++ {
        switch i {
        case 0, 2:
            t.Log("Even")
        case 1, 3:
            t.Log("Odd")
        default:
            t.Log("it not in 0-3")
        }
    }
}

func TestSwitchCaseCondition(t *testing.T) {
    for i := 0; i < 5; i++ {
        switch {
        case i%2 == 0:
            t.Log("Even")
        case i%2 == 1:
            t.Log("Odd")
        default:
            t.Log("it not in 0-3")
        }
    }
}

3-1 运行结果: 2.4 循环和条件

3-2 运行结果: 2.4 循环和条件

点赞
收藏
评论区
推荐文章

暂无数据