gocolon-equals

What is the difference between := and = in Go?


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 =?


Solution

  • = 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