Learn Go Programming

Visual, concise and detailed tutorials, tips and tricks about Go (aka Golang).

Follow publication

Short variable declarations rulebook

How to use short variable declarations properly.

Inanc Gumus
Learn Go Programming
2 min readOct 4, 2017

👉 You can’t use it to declare package-level variables.

illegal := 42func foo() {
legal := 42
}

Because, at package level, every declaration should start with a keyword like var, const, func, type, and import.

👉 You can’t use it twice:

legal := 42
legal := 42 // <-- error

Because, := introduces "a new variable", hence using it twice does not redeclare a second variable, so it's illegal.

👉 You can use them twice in “multi-variable” declarations if one of the variables are new:

foo, bar  := someFunc()
foo, jazz := someFunc() // <-- jazz is new
baz, foo := someFunc() // <-- baz is new

This is legal, because, you’re not redeclaring variables, you’re just reassigning new values to the existing variables, with some new variables.

👉 You can use them if a variable already declared with the same name before:

var foo int = 34func some() {
// because foo here is scoped to some func
foo := 42 // <-- legal
foo = 314 // <-- legal
}

Here, foo := 42 is legal, because, it redeclares foo in some() func's scope. foo = 314 is legal, because, it just reassigns a new value to foo.

👉 You can use them for multi-variable declarations and assignments:

foo, bar   := 42, 314
jazz, bazz := 22, 7

👉 You can reuse them in scoped statement contexts like if, for, switch:

foo := 42
if foo := someFunc(); foo == 314 {
// foo is scoped to 314 here
// ...
}
// foo is still 42 here

Because, if foo := ... assignment, only accessible to that if clause.

Alright, that’s all for now. Thank you for reading so far.

Let’s stay in touch:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in Learn Go Programming

Visual, concise and detailed tutorials, tips and tricks about Go (aka Golang).

Written by Inanc Gumus

Coder. Gopher. Maker. Stoic. Since 1992.

Responses (4)

Write a response