I am new to Go programming language.
I noticed something strange in Go: I thought that it used :=
and substitutes =
in Python, but when I use =
in Go it is also works.
What is the difference between :=
and =
?
As others have explained already, := is for both declaration, and assignment, whereas = is for assignment only. For example, var abc int = 20 is the same as abc := 20. It's useful when you don't want to fill up your code with type or struct declarations. Follow this answer to receive notifications.
Expanded assignment = defines a recursively-expanded variable. := defines a simply-expanded variable.
“&a” simply denotes that the system is to provide the memory address of the variable a. A reference if you will. So, what is & in golang? var b *string declares that whatever is assigned to “b” must be a pointer memory address.
= operator assigns a value either as a part of the SET statement or as a part of the SET clause in an UPDATE statement, in any other case = operator is interpreted as a comparison operator. On the other hand, := operator assigns a value and it is never interpreted as a comparison operator.
=
is assignment. more about assignment in Go: Assignments
The subtle difference between =
and :=
is when =
used in variable declarations.
General form of variable declaration in Go is:
var name type = expression
the above declaration creates a variable of a particular type, attaches a name to it, and sets its initial value. Either the type
or the = expression
can be omitted, but not both.
For example:
var x int = 1 var a int var b, c, d = 3.14, "stackoverflow", true
:=
is called short variable declaration
which takes form
name := expression
and the type of name is determined by the type of expression
Note that: :=
is a declaration, whereas =
is an assignment
So, a short variable declaration must declare at least one new variable. which means a short variable declaration doesn't necessarily declare all the variables on its left-hand side, when some of them were already declared in the same lexical block, then :=
acts like an assignment to those variables
For example:
r := foo() // ok, declare a new variable r r, m := bar() // ok, declare a new variable m and assign r a new value r, m := bar2() //compile error: no new variables
Besides, :=
may appear only inside functions. In some contexts such as the initializers for "if", "for", or "switch" statements, they can be used to declare local temporary variables.
More info:
variable declarations
short variable declarations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With