Is there a difference between these 2 styles of variable declaration/initialization?
package main
import "fmt"
func main() {
var a = "I am a string" // Declare + init (infer)
fmt.Println(a)
b := "I am a string" // Declare + init (shorthand)
fmt.Println(b)
}
I fail to see the added value of the shorthand syntax, and inclined to use the "var" statement for consistency throughout my code.
I only use var when necessary, like:
1) global variables
2) if statement like:
var err error
if x == nil {
err = errors.New("x is nil")
} else if y == nil {
err = errors.New("y is nil")
}
...
I always try to use the :=
syntax. The benefit is huge when you need to Refactor code.
You are not binding the name of the variable to any particular type and any time you change the right hand side's type the variable would automatically infer the new type.