1 回答
TA贡献1884条经验 获得超4个赞
重要的部分是“将从右侧推断”[作业的]。
您只需要在声明但不分配变量时指定类型,或者如果您希望类型与推断的类型不同。否则,变量的类型将与赋值右侧的类型相同。
// 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{
...
}
- 1 回答
- 0 关注
- 265 浏览
添加回答
举报