Assignment operator in Go language

Solution 1:

The := notation serves both as a declaration and as initialization.

foo := "bar"

is equivalent to

var foo = "bar"

Why not using only foo = "bar" like in any scripting language, you may ask ? Well, that's to avoid typos.

foo = "bar"
fooo = "baz" + foo + "baz"   // Oops, is fooo a new variable or did I mean 'foo' ?

Solution 2:

name := "John"

is just syntactic sugar for

var name string
name = "John"

Go is statically typed, so you have to declare variables.

Solution 3:

:= is not the assignment operator. It's a short variable declaration. = is the assignment operator.

Short variable declarations

A short variable declaration uses the syntax:

ShortVarDecl = IdentifierList ":=" ExpressionList .

It is a shorthand for a regular variable declaration with initializer expressions but no types:

"var" IdentifierList = ExpressionList .

Assignments

Assignment = ExpressionList assign_op ExpressionList .

assign_op = [ add_op | mul_op ] "=" .

In Go, name := "John" is shorthand for var name = "John".