Why can I redefine the same variable several times in a for loop, but cannot outside the loop?

I have the following program.

package main

import (
    "fmt"
)

func main() {
    for i := 0; i < 2; i++ {
        x := 77
        fmt.Println(x)
    }
}

Upon execution, I received:

77
77

As we can see, it x := 77was performed 2 times. However, if I change it a bit like this:

package main

import (
    "fmt"
)

func main() {
    a := 77
    fmt.Println(a)
    a := 77
    fmt.Println(a)
}

I will get the error "there are no new variables on the left side :=." Why is this?

+8
source share
2 answers

There are a couple of things. First, let me turn to the second half of your question.

By default, a keyword is used to declare a variable var, and then assigned to it using an operator =.

var a int
a = 77

Go :=,

a := 77

, := , a , . no new variables on left side of := .

, for?

, , {}, . x , , . , .

,

{
    x := 77
    fmt.Println(x)
}
fmt.Println(x) // Compile error

Println , x .

+11

 , ,  .

: : = = Go?


for ,
x ( Go):

package main

import (
    "fmt"
)

func main() {
    for i := 0; i < 2; i++ {
        x := 77
        fmt.Println(&x)
    }
}

:

0x1040e0f8
0x1040e0fc

, ( Go:

package main

import (
    "fmt"
)

func main() {
    a := 77
    fmt.Println(&a)
    {
        a := 77
        fmt.Println(&a)
    }
}

:

0x1040e0f8
0x1040e0fc

.: Scope Shadowing Go?

+2

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


All Articles