在 golang switch 语句中更改变量值

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

这是预期的行为吗?


烙印99
浏览 156回答 2
2回答

临摹微笑

该fallthrough语句将控制权转移到下一个case块的第一条语句。该fallthrough语句并不意味着继续计算 next 的表达式case,而是无条件地开始执行下一个case块。引用fallthrough声明文档:“fallthrough”语句将控制转移到表达式“switch”语句中下一个 case 子句的第一个语句。引用switch声明文档:在 case 或 default 子句中,最后一个非空语句可能是(可能标记为)“fallthrough”语句,以指示控制应该从该子句的末尾流向下一个子句的第一个语句。否则控制流到“switch”语句的末尾。

慕森王

是的,正如 icza 所指出的那样。如果您不想在第一个 case 块之后落入每个 case 块,请删除fallthrough行(就像您不会break在每个 C/C++ case 块的末尾放置一行。而且,正如您在评论中所期望的那样,评估在switch()达到时完成,之后无论您是否更改i值,都不会在每个案例块上再次评估。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go