Where can we use Variable Scoping and Shadowing in Go?

Some related posts I found:

There are also many uses for the Scope and Shadowing variables.
Any code samples or answers will be appreciated.

+1
source share
1 answer

Variable Visibility and Shading:

Go has a lexical area using blocks:

  • The scope of the predefined identifier is the universe block.
  • , , , ( ), ( ) .
  • package - , .
  • , , - .
  • , ConstSpec VarSpec (ShortVarDecl ) .
  • , TypeSpec .
    , , .
    , , .

; . - , .

:

  • ,

Go:

  • Golang ( ):

    package main
    import "fmt"
    func main() {
        i := 10 //scope: main
        j := 4
        for i := 'a'; i < 'b'; i++ {
            // i shadowed inside this block
            fmt.Println(i, j) //97 4
        }
        fmt.Println(i, j) //10 4
    
        if i := "test"; len(i) == j {
            // i shadowed inside this block
            fmt.Println(i, j) // i= test , j= 4
        } else {
            // i shadowed inside this block
            fmt.Println(i, j) //test 40
        }
        fmt.Println(i, j) //10 4
    }
    
  • " ", .
    , :

    { }:
    : , , , ,...

    package main
    import "fmt"
    func main() {
        i := 1
        j := 2
        //new scope :
        {
            i := "hi" //new local var
            j++
            fmt.Println(i, j) //hi 3
        }
        fmt.Println(i, j) //1 3
    }
    
  • :
    : , ,
    : / :

    package main
    import "fmt"
    func fun(i int, j *int) {
        i++                //+nice: use as local var without side effect
        *j++               //+nice: intentionally use as global var
        fmt.Println(i, *j) //11 21
    }
    func main() {
        i := 10 //scope: main
        j := 20
        fun(i, &j)
        fmt.Println(i, j) //10 21
    }
    
  • :

    package main
    import "fmt"
    var i int = 1 //global
    func main() {
        j := 2
        fmt.Println(i, j) //1 2
        i := 10           //Shadowing global var
        fmt.Println(i, j) //10 2
        fun(i, j)         //10 2
    }
    func fun(i, j int) {
        //i := 100        //error: no new variables on left side of :=
        //var i int = 100 //error: i redeclared in this block
        fmt.Println(i, j) //10 2
    }
    

: Scope > .
:
:

+4

Source: https://habr.com/ru/post/1652871/


All Articles