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 Answer
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 applies
var 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{
...
}
1 Comment
Ainar-G
I think it's also worth noting that you can only use the
var x (type) = foo() form in the global scope.