Move variable area and shading

This is an example from the GOPL - "the expressions x [i] and x + 'A' - 'a' each refer to the declaration x from an external block, we will explain this in a moment."

An explanation never comes. Why does x [i] refer to x in the outer scope? As soon as you update x in the inner block, it should shadow x in the outer block. Why does it work?

package main

import "fmt"

func main() {
    x := "hello!"
    for i := 0; i < len(x); i++ {
        x := x[i]
        if x != '!' {
            x := x + 'A' - 'a'
            fmt.Printf("%c", x)
        }
    }
}

http://play.golang.org/p/NQxfkTeGzA

+2
source share
1 answer
Operator

:= creates a new variable and assigns it the value of the right hand.

for x := x[i] x, , x, x := "hello!". , x .

x .

. x := x[i].

x. .

.

+4

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


All Articles