【发布时间】: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