Assignment and declaration syntax sugar
Slightly basic usage, you can search
Precautions
Type inference
:=
Will automatically type inference, when you want to type is not what you want type needs to be cast
// i1 默认是 int 类型
i1 := 1
// 当需要把 i2 当成 int64 来使用时需要进行类型转换再赋值
i2 := int64(1)
Here comes type inference, mention const variable, if the value of the variable const automatically defined according to the context determined automatically compile type
With the scope of the existing variable does not re-create a new variable
:=
The variable on the left are not necessarily all new variable, it may be old variables, only to be re-assignment of it, as long as the existing variable with scope, does not create a new variable
// 返回 1
func testFunc() (ret int) {
ret, err := 1, error(nil)
if err != nil {
return
}
return
}
Different will create a new variable scope
Area with little to separate the top
// 返回 0, 返回值的 ret 并没有被赋值, 赋值的是 if 里面的 ret, 和外面的 ret 并不相关
func testFunc() (ret int) {
if ret, err := 1, error(nil); err != nil {
fmt.Println(ret)
return
}
return
}