hi all, I’m kind of studying Golang, and I have a question.
here’s a simple code for a test go program:
package main
import (“fmt”
)
var (
john string
mike string
c = “dce”
)
func main() {
john := “john”
c = “A”
c := “B”
i := 10
fmt.Println(“i”,i,john,c)
c := “C”
}
notice the variable ‘c’.
I have assigned “A” to it, then used := operator to declare and set it to “B”
The code works without any error, but if I use := again for setting it to “C”, then golang throws an error.
Shouldn’t it supposed to throw the Error when it tried to set it to “B”, as the c is already assigned with a value?
I thought := is used only when a variable has not yet been initialized, so hence my question.
Okay, but that’s kind of weird, I would say regardless of whether the variable is from global or local, due to the definition of what := implies, the compile should return error, don’t you think? Not sure what’s the benefit of allowing this to happen…
To keep it simple, you bumped into the consequences of using global variable. In Go, you’re allowed to declare a local variable with the same name of global variable, but loses the ability to access the global counterpart.
Consider:
package main
import (
"fmt"
)
var (
a = "Hello"
b = "World"
)
func globalCheck() {
fmt.Printf("GLOBAL: %v %v\n", a, b)
}
func main() {
fmt.Printf("AFTER : %v %v\n", a, b)
globalCheck()
}
// Output:
// AFTER : Hello World
// GLOBAL: Hello World
This is where you access both global variables. Now, inside main, we declare another a variable, this time it is local to main.
package main
import (
"fmt"
)
var (
a = "Hello"
b = "World"
)
func globalCheck() {
fmt.Printf("GLOBAL: %v %v\n", a, b)
}
func main() {
a := "Bonjour"
fmt.Printf("AFTER : %v %v\n", a, b)
globalCheck()
}
// Output:
// AFTER : Bonjour World
// GLOBAL: Hello World
If you change the variable a inside main, you get to set the local version.
package main
import (
"fmt"
)
var (
a = "Hello"
b = "World"
)
func globalCheck() {
fmt.Printf("GLOBAL: %v %v\n", a, b)
}
func main() {
a := "Bonjour"
fmt.Printf("BEFORE: %v %v\n", a, b)
a = "你好"
fmt.Printf("AFTER : %v %v\n", a, b)
globalCheck()
}
// Output:
// BEFORE: Bonjour World
// AFTER : 你好 World
// GLOBAL: Hello World
Hence, if you use the := operator after declaring the local variable a inside main again, it will give you a compilation error, stating that a has already exists.
package main
import (
"fmt"
)
var (
a = "Hello"
b = "World"
)
func globalCheck() {
fmt.Printf("GLOBAL: %v %v\n", a, b)
}
func main() {
a := "Bonjour"
fmt.Printf("BEFORE: %v %v\n", a, b)
a := "你好"
fmt.Printf("AFTER : %v %v\n", a, b)
globalCheck()
}
// Output:
// # command-line-arguments
// ./main.go:19:4: no new variables on left side of :=
How to access back to global
Do not use global variable at the first place (recommended)
Avoid naming conflict. Note that you can’t stop your consumers from repeating this problem.
Use a setter/getter function. Example, globalCheck() is a getter function.