在 Golang 的 switch 语句中修改变量的值。

huangapple go评论67阅读模式
英文:

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)
	}
}

Output:

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

Is this expected behavior?

答案1

得分: 4

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

fallthrough语句不会继续评估下一个case的表达式,而是无条件地开始执行下一个case块。

引用自fallthrough语句文档:

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

引用自switch语句文档

> 在case或default子句中,最后一个非空语句可以是(可能是带标签的)“fallthrough”语句,以指示控制应从该子句的末尾流向下一个子句的第一条语句。否则,控制流将流向“switch”语句的末尾。

英文:

The fallthrough statement transfers control to the first statement of the next case block.

The fallthrough statement does not mean to continue evaluating the expression of the next case, but to unconditionally start executing the next case block.

Quoting from fallthrough statement doc:

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

Quoting from 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.

答案2

得分: 0

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

如果你不想在第一个case块之后执行每个case块,可以删除fallthrough语句(就像你没有在每个C/C++ case块的末尾放置break语句一样)。

而且,正如你在注释中所期望的那样,在达到switch()语句时进行评估,之后无论你如何更改i的值,它都不会在每个case块中再次被评估。

英文:

Yes it is, as pointed by icza.

If you don't want to fall under every case block after first, remove fallthrough lines (it's like you wouldn't have put a break line at the end of each C/C++ case block.

And, as you expect in comments, the evaluation is done when switch() is reached, after that it doesn't matter if you change i value, it won't be evaluated again on each case block.

huangapple
  • 本文由 发表于 2021年11月10日 19:22:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/69912423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定