I'm trying to understand why in Go the following code does not produce an error.
func main() {
foo := foo()
fmt.Println(foo)
}
func foo() int {
return 1
}
Foo is already defined in the global scope, why am I able to redefine it ?
https://golang.org/ref/spec#Declarations_and_scope
An identifier declared in a block may be redeclared in an inner block. While the identifier of the inner declaration is in scope, it denotes the entity declared by the inner declaration.
It’s possible to redeclare an identifier in an inner block.Program produces an error if the same identifier is declared twice in the same block.
Consider this example for understanding the scope:
package main
import "fmt"
var v="global"
func main() {
v := v
fmt.Println(v)
//v := v
//Error: Same identifier 'v' declared again
{
v := "inner"
fmt.Println(v)
}
fmt.Println(v)
}
Output of the Program:
global
inner
global