Go provides `:=` operator to make declaring variables easier. It is a [shorthand to declare and set a value of a variable](https://golang.org/ref/spec#Short_variable_declarations). for example,
```go
varxint
x=42
```
can be written as
```go
x:=42
```
But if not careful, this can accidently shadow variable bindings. Let's look at the fictitious piece of code.
```go
packagemain
import"fmt"
funcfictitiousFunc()(int,error){
return42,nil
}
funcmain(){
x:=10;
x,err:=fictitiousFunc()
iferr!=nil{
fmt.Println("I'll never print")
}
fmt.Println("value of x: ",x)
}
```
This produces following output
```
value of x: 42
```
While, this following piece of code will fail to compile
```go
packagemain
import"fmt"
funcfictitiousFunc()(int,error){
return42,nil
}
funcmain(){
x:=10
// replace :=
varxint
varerrerror
x,err=fictitiousFunc()
iferr!=nil{
fmt.Println("I'll never print")
}
fmt.Println("value of x: ",x)
}
```
output:
```
prog.go:12: x redeclared in this block
previous declaration at prog.go:10
```
So we can see that the operator is somewhat intelligent, and does not redeclare the variables.
Now what if we push it down a scope? See the following code
```go
packagemain
import"fmt"
funcfictitiousFunc()(int,error){
return42,nil
}
funcmain(){
someCondition:=true
x:=-1;
ifsomeCondition{
x,err:=fictitiousFunc()
iferr!=nil{
fmt.Println("I'll never print")
}
fmt.Println("value of x inside: ",x)
}
fmt.Println("value x outside: ",x)
}
```
This produces,
```go
valueofxinside:42
valuexoutside:-1
```
At line: 16, since the immediate scope (line:15-32) does not have variable `x` declared, `:=` is redeclaring the variable. a.k.a the __variable `x` gets shadowed__.
Only workaround I can think of is not to use `:=`, i.e change the code to