DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Inanc Gumus
Inanc Gumus

Posted on

Short variable declaration rules

#go

This is a spin-off post from my main post of Visual how to guide to Go variables, go check it out.


Γ°ΕΈβ€˜β€° You can’t use it to declare package-level variables.

illegal := 42
func foo() {
  legal := 42
}
Enter fullscreen mode Exit fullscreen mode

Γ°ΕΈβ€˜β€° You can’t use it twice:

legal := 42
legal := 42 // <-- error
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 = 34
func some() {
  // because foo here is scoped to some func
  foo := 42  // <-- legal
  foo = 314  // <-- legal
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Γ°ΕΈβ€˜β€° 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
Enter fullscreen mode Exit fullscreen mode

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


ҝ€ï¸ Share this on twitter. Please share the love.
🐦 I’m mostly tweeting about Go, you can follow me on twitter: @inancgumus.
ðŸ”Β₯ I’m also creating an online course to teach Go. Join to my newsletter!
You will receive notifications about my new posts and upcoming online Go course (every Wednesday).


Originally published on Go Short Variable Declaration Rules in Learn Go Programming.

Top comments (0)

Become a Moderator Do you want us to help make DEV a better place?

Fill out this survey and help us by becoming a tag moderator here at DEV.