This question already has an answer here:
Is there any difference between the following two examples?
type Example struct {}
func main() {
e := Example{}
}
vs.
type Example struct {}
func main() {
var e Example
}
Is there a preferable one?
Thanks!
</div>
Might worth noting:
Use :=
when you need to create a variable with a defined value on it.
number := 12
obj := SomeStruct{name: "user"}
slice := []string{"a", "b", "c"}
Use var
keyword when you need to define a variable without any initialisation, so the zero value will be used on it.
var a int // the default value will be the zero value of int, which is 0
var mut sync.Mutex
var result []map[string]interface{}
Also there is another advantage of using var
keyword, like we can create multiple variable with one type in one line.
var result1, result2, result3, result4 []map[string]interface{}
var
is mostly used to define variables in a shared scope. For example,
var something string
func init() {
something = "Hello world!"
}
func main() {
fmt.Println(something)
}
Have no different in here, just a habit. I often use var e Example
.:=
can not using outside function while var
can do it.