在 golang switch 语句中更改变量值

Changing variable value inside golang switch statement

package main

import "fmt"

func main() {
    var i int = 10
    switch true {
    case i < 20:
        fmt.Printf("%v is less than 20\n", i)
        i = 100
        fallthrough
    case i < 19:
        fmt.Printf("%v is less than 19\n", i)
        fallthrough
    case i < 18:
        fmt.Printf("%v is less than 18\n", i)
        fallthrough
    case i > 50:
        fmt.Printf("%v is greater than 50\n", i)
        fallthrough
    case i < 19:
        fmt.Printf("%v is less than 19\n", i)
        fallthrough
    case i == 100:
        fmt.Printf("%v is equal to 100\n", i)
        fallthrough
    case i < 17:
        fmt.Printf("%v is less than 17\n", i)
    }
}

输出:

10 is less than 20
100 is less than 19
100 is less than 18
100 is greater than 50
100 is less than 19
100 is equal to 100
100 is less than 17

这是预期的行为吗?

fallthrough 语句将控制转移到下一个 case 块的第一条语句。

fallthrough语句并不是继续计算下一个case的表达式,而是无条件开始执行下一个case ]块。

引用自 fallthrough 声明文档:

A "fallthrough" statement transfers control to the first statement of the next case clause in an expression "switch" statement.

引用自switch statement doc

In a case or default clause, the last non-empty statement may be a (possibly labeled) "fallthrough" statement to indicate that control should flow from the end of this clause to the first statement of the next clause. Otherwise control flows to the end of the "switch" statement.

是的,正如 icza 指出的那样。

如果您不想在 first 之后属于每个案例块,请删除 fallthrough 行(就像您不会在每个 [= 的末尾放置 break 行一样20=]++ 案例块。

并且,正如您在评论中所期望的那样,在达到 switch() 时完成评估,之后如果您更改 i 值则无所谓,不会再次评估在每个案例块上。