switch case 内变量的范围

Eri*_*ang 1 scope go

package main

import "fmt"

func main() {
    x := 10
    switch x {
    case 0:
        y := 'a'
        fmt.Printf("%c\n", y)
    case 1:
        // y = 'b' // this can't compile,
        y := 'b'
        fmt.Printf("%c\n", y)
    default:
        y := '-'
        fmt.Printf("%c\n", y)
    }
}
Run Code Online (Sandbox Code Playgroud)

似乎y每个case都是包含的本地的case,对其他情况不可见。我所知:

  • {}可以创建本地范围,但没有{}每个case.
  • Java 则不同。

我在网上查了一下,没有得到明确的定义。我知道我们可以initializationswitch.

问题

  1. 你能确认,在 Golang 中,switch 内的变量范围case是 case 本身的局部范围吗?
  2. 这是一个特殊的设计吗,如上所述,没有{}每个case.

icz*_*cza 5

规格: 块:

块是匹配大括号内的可能为空的声明和语句序列。

Block = "{" StatementList "}" .
StatementList = { Statement ";" } .
Run Code Online (Sandbox Code Playgroud)

源代码中除了显式块之外,还有隐式块:

  1. Universe包含所有 Go 源文本。
  2. 每个都有一个包块,其中包含该包的所有 Go 源文本。
  3. 每个文件都有一个文件块,其中包含该文件中的所有 Go 源文本。
  4. 每个“if”“for”“switch”语句都被视为位于其自己的隐式块中。
  5. “switch”“select”语句中的每个子句都充当隐式块。

块嵌套并影响范围。

正如您在规范中看到的:每个子句(例如case)充当隐式块,无需显式使用{}