In Go variable declarations are followed by the intended type, for example var x string = "I am a string", but I am using Atom text editor with the go-plus plugin and go-plus suggests that I "should omit type string from declaration of var x; it will be inferred from the right-hand side". So basically, the code still compiles without specifying x's type? So is it unnecessary to specify variable types in Go?
1条回答 默认 最新
- doudouwd2017 2016-01-21 16:45关注
The important part is "will be inferred from the right-hand side" [of the assignment].
You only need to specify a type when declaring but not assigning a variable, or if you want the type to be different than what's inferred. Otherwise, the variable's type will be the same as that of the right-hand side of the assignment.
// 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")
Outside of a function body at the global scope, you can't use
:=
, but the same type inference still appliesvar s = "this is still a string"
The last case is where you want the variable to have a different type than what's inferred.
// 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{ ... }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报