在 Go 中,变量声明后跟预期的类型,例如 var x string = "I am a string",但我使用带有 go-plus 插件的 Atom 文本编辑器并且 go-plus 建议我“应该省略从 var x 的声明中键入字符串;将从右侧推断出来”。所以基本上,代码仍然可以在不指定 x 类型的情况下编译?那么Go中是不是不需要指定变量类型呢?
最佳答案
重要的部分是“将从右侧推断”[赋值]。
您只需要在声明但不分配变量时指定类型,或者如果您希望类型不同于推断的类型。否则,变量的类型将与赋值右侧的类型相同。
// s and t are strings
s := "this is a string"
// this form isn't needed inside a function body, but works the same.
var t = "this is another string"
// x is a *big.Int
x := big.NewInt(0)
// e is a nil error interface
// we specify the type, because there's no assignment
var e error
// resp is an *http.Response, and err is an error
resp, err := http.Get("http://example.com")
在全局作用域的函数体之外,你不能使用:=
,但同样的类型推断仍然适用
var s = "this is still a string"
最后一种情况是您希望变量的类型不同于推断的类型。
// we want x to be an uint64 even though the literal would be
// inferred as an int
var x uint64 = 3
// though we would do the same with a type conversion
x := uint64(3)
// Taken from the http package, we want the DefaultTransport
// to be a RoundTripper interface that contains a Transport
var DefaultTransport RoundTripper = &Transport{
...
}
关于go - 在不指定类型的情况下在 Go 中声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34929344/