Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variables in Go without specifying type

Tags:

go

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?

like image 740
Mahmud Adam Avatar asked Dec 27 '25 16:12

Mahmud Adam


1 Answers

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{
    ...
}
like image 135
JimB Avatar answered Dec 31 '25 19:12

JimB