在 Go 变量声明后面跟着预期的类型,例如 var x string = "I am a string",但我使用的是带有 go-plus 插件的 Atom 文本编辑器,go-plus 建议我“应该从var x 的声明;它将从右侧推断”。所以基本上,代码仍然编译而不指定 x 的类型?那么在Go中是不是没有必要指定变量类型呢?
慕莱坞森
浏览 266回答 1
1回答
慕村9548890
重要的部分是“将从右侧推断”[作业的]。您只需要在声明但不分配变量时指定类型,或者如果您希望类型与推断的类型不同。否则,变量的类型将与赋值右侧的类型相同。// s and t are stringss := "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.Intx := big.NewInt(0)// e is a nil error interface// we specify the type, because there's no assignmentvar e error// resp is an *http.Response, and err is an errorresp, 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 intvar 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 Transportvar DefaultTransport RoundTripper = &Transport{ ...}