Home >Backend Development >Golang >Scope of variables within switch case

Scope of variables within switch case

WBOY
WBOYforward
2024-02-09 09:00:21703browse

switch case 内变量的范围

php Xiaobian Yuzai will introduce to you the scope of variables in the switch case statement. In the switch case statement, the scope of the variable is limited to the current case block and will not affect other case blocks. This means that even if the same variable name is used in different case blocks, they are independent of each other and will not cause conflicts. This feature allows us to use the same variable name in different case blocks without worrying about errors or conflicts. Therefore, when writing switch case statements, we can operate variables more flexibly and improve the readability and maintainability of the code.

Question content

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

It seems that y in each case is a local file containing case and is not visible to other cases. as far as I know:

  • {} It is possible to create local scopes, but not {} per case.
  • Java is different.

I checked online and found no clear definition. I know we can declare switch scope variables in the initialization section of switch.

question:

  1. Can you confirm that in Golang, the variable scope within the switch case is local to the case itself?
  2. Is this a special design? Each case mentioned above does not have {}.

Solution

Specification: Block:

As you can see in the specification: each clause (e.g. case) acts as an implicit block without the need to explicitly use {}.

The above is the detailed content of Scope of variables within switch case. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete