Yesterday we saw how to define variables with var, but if you’ve ever actually used Go, you probably know that’s not actually the most common way to define variables. Let’s take a look at the alternative…
Short variable declarations
A short variable declaration uses the syntax:
ShortVarDecl = IdentifierList ":=" ExpressionList .It is shorthand for a regular variable declaration with initializer expressions but no types:
"var" IdentifierList "=" ExpressionList .i, j := 0, 10 f := func() int { return 7 } ch := make(chan int) r, w, _ := os.Pipe() // os.Pipe() returns a connected pair of Files and an error, if any _, y, _ := coord(p) // coord() returns three values; only interested in y coordinate
So in other words, you can use the := assignment operator as a shorthand for certain uses of var. We saw some great examples above, but let me expand on them by showing what the longhand form of each would look like, for direct comparsion.
i, j := 0, 10 // Shorthand
var i, j = 0, 10 // Long form
f := func() int { return 7 }
var f = func() int { return 7 }
ch := make(chan int)
var ch = make(chan int)
r, w, _ := os.Pipe()
var r, w, _ = os.Pipe()
_, y, _ := coord(p)
var _, y, _ = coord(p)
Simple, eh? Notably, and as mentioned in the spec quoted above, there’s no option to specify a type in the variable declaration this way. Although you can git around this in some cases, by specifying the type on the right hand side:
i := int(3)
Tomorrow we’ll look at some of the other implications, and limitations, of the short variable declaration.
Quotes from The Go Programming Language Specification Version of August 2, 2023