【问题标题】:Changing variable value inside golang switch statement在 golang switch 语句中更改变量值
【发布时间】:2023-03-28 23:45:01
【问题描述】:
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 根据语言规范的预期行为。你的期望是什么? - golang.org/ref/spec#Switch_statements(在表达式开关下)
  • fmt.Println("1 equals 0") 打印 1 equals 0 是的,这是预期的行为。
  • 我的期望是当我在第一个表达式中更改“i”的值时,它将在下一个“case”中进行评估。

标签: go switch-statement


【解决方案1】:

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

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

引自fallthrough声明文档:

“fallthrough”语句将控制转移到表达式“switch”语句中下一个 case 子句的第一条语句。

引用switch statement doc:

在 case 或 default 子句中,最后一个非空语句可能是(可能是labeled"fallthrough" statement,以指示控制应该从该子句的末尾流向下一个子句的第一个语句。否则控制流到“switch”语句的末尾。

【讨论】:

  • 感谢您的出色回答。无论如何,如果在下一个“案例”中进行评估,那不是很好吗?为什么不应该评估?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多