是的,你可以,而且它比看起来更微妙。
首先,你可以做一些简单的事情:
var a, b, x, y int // declares four variables all of type int
您可以在函数参数声明中使用相同的语法:
func foo(a, b string) { // takes two string parameters a and b
...
}
然后是同时声明和分配变量的简写语法。
x, y := "Hello", 10 // x is an instance of `string`, y is of type `int`
Golang 中经常遇到的模式是:
result, err := some_api(...) // declares and sets `result` and `err`
if err != nil {
// ...
return err
}
result1, err := some_other_api(...) // declares and sets `result1`, reassigns `err`
if err != nil {
return err
}
因此,您可以分配给:= 运算符左侧的已定义变量,只要分配给的变量中至少有一个是新的。否则,它的格式不正确。这很漂亮,因为它允许我们为多个 API 调用重用相同的错误变量,而不必为每个 API 调用定义一个新变量。但请注意不要无意中使用以下内容:
result, err := some_api(...) // declares and sets `result` and `err`
if err != nil {
// ...
return err
}
if result1, err := some_other_api(...); err != nil { // result1, err are both created afresh,
// visible only in the scope of this block.
// this err shadows err from outer block
return err
}