What is the difference between := and = in Go?
Asked Answered
M

8

74

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

Mikey answered 9/4, 2016 at 4:58 Comment(1)
tour.golang.org/basics/10Mapel
A
88

= 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

Abuttals answered 9/4, 2016 at 5:47 Comment(3)
so inside { } using := means declare new variable even though there is the same variable with the same name outside enclosed { } ?Mikey
yes, it is a new one. a {} is a lexical block, different lexical block is different scope. But use the same name is usually not a good style in practice. @MikeyAbuttals
Thank you. I've been curious but this answered my question: at least one new variable. So not necessarily all of them.Treytri
W
14

= is just assignment

:= is declare-and-initialize construct for new vars (at least one new var) inside the function block (not global):

var u1 uint32      //declare a variable and init with 0
u1 = 32            //assign its value
var u2 uint32 = 32 //declare a variable and assign its value at once
//declare a new variable with defining data type:
u3 := uint32(32)        //inside the function block this is equal to: var u3 uint32 = 32
fmt.Println(u1, u2, u3) //32 32 32
//u3 := 20//err: no new variables on left side of :=
u3 = 20
fmt.Println(u1, u2, u3) //32 32 20
u3, str4 := 100, "str"        // at least one new var
fmt.Println(u1, u2, u3, str4) //32 32 100 str
Warrigal answered 9/4, 2016 at 5:30 Comment(0)
T
6

:= is the "short declaration form" for declaring and initializing variables. It does type inference on the value that you are assigning to set the variable's type.

If you attempt to assign with the short declaration form to the same variable in the same scope, the compiler will throw an error.

Be on the lookout for the short declaration form "shadowing" the same variable in an enclosing scope (especially with errors)

= requires the var keyword when declaring a variable and the variable's type explicitly following the variable name. You can actually leave the = off the declaration since Go has a initial value for all types (strings are initialized as "", ints are 0, slices are empty slices). It can also be used for reassignment with just a value, ie

var s string = "a string" // declared and initialized to "a string"
s = "something else"      // value is reassigned

var n int // declared and initialized to 0
n = 3
Tricuspid answered 9/4, 2016 at 5:30 Comment(0)
I
4

The most verbose way to declare a variable in Go uses the var keyword, an explicit type, and an assignment.

var x int = 10

Go also supports a short declaration format. When you are within a function, you can use the := operator to replace a var declaration that uses type inference.

var x = 10
x := 10

There is one limitation on :=. If you are declaring a variable at package level, you must use var because := is not legal outside of functions.

There are some situations within functions where you should avoid :=

  • When initializing a variable to its zero value, use var x int. This makes it clear that the zero value is intended.
  • When assigning an untyped constant or a literal to a variable and the default type for the constant or literal isn’t the type you want for the variable, use the long var form with the type specified. While it is legal to use a type conversion to specify the type of the value and use := to write x := byte(20), it is idiomatic to write var x byte = 20.
  • Because := allows you to assign to both new and existing variables, it sometimes creates new variables when you think you are reusing existing ones. In those situations, explicitly declare all of your new variables with var to make it clear which variables are new, and then use the assignment operator (=) to assign values to both new and old variables.

While var and := allow you to declare multiple variables on the same line, only use this style when assigning multiple values returned from a function or the comma ok idiom.

Learning Go Jon Bondner

Intra answered 1/2, 2022 at 5:37 Comment(0)
C
3

Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

for example:

package main

import "fmt"

func main() {
    var i, j int = 1, 2
    k := 3
    c, python, java := true, false, "no!"

    fmt.Println(i, j, k, c, python, java)
}

NOTICE: the variable declared with := can only be used inside the function block.

Corolla answered 9/4, 2016 at 5:17 Comment(0)
C
1

I took time to figure out a mistake I made that could help you to clarify the difference between := and =. Consider the following code:

type mystruct struct {
    a int
    arr []int
}

func main() {   
    m := mystruct{}
    m.arr := make([]int, 5) //compilation error because m.arr is already declared.
    m.arr = make([]int, 5)  //compiles

}
Coverall answered 22/11, 2018 at 16:42 Comment(0)
S
0

= is used as statically typed.

:= is used as dynamically typed.

example:

var a = 30   # statically typed and is a compile time check

b := 40      # dynamically checked. 
Saddlebow answered 20/4, 2021 at 5:15 Comment(0)
D
0

Note the difference in := and = in range clauses as well. The following examples are adapted from the spec.

The iteration variables may be declared by the "range" clause using a form of short variable declaration (:=). In this case their types are set to the types of the respective iteration values and their scope is the block of the "for" statement; they are re-used in each iteration. If the iteration variables are declared outside the "for" statement, after execution their values will be those of the last iteration.

= range ...:

i := 2
x = []int{3, 5, 7}
for i, x[i] = range x {  // i,x[2] = 0,x[0]
    break
}
// now i == 0 and x == []int{3, 5, 3}
var (key string; val interface{})
m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6}
for key, val = range m {
    h(key, val)
}
// key == last map key encountered in iteration (note order of map iteration is random)
// val == map[key]

:= range ...:

var a [10]string
for i, s := range a {
    // type of i is int, type of s is string
    // s == a[i]
    someFunction(i, s)
}
// i and s are no longer accessible here.
for i := range a { // roughly equivalent to `for i := 0; i < len(a); i++`
    someFunction(i, a[i])
}
for _, s := range a {
    anotherFunc(s)
}
// Above is roughly equivalent to:
{
    var s string
    for i := 0; i < len(a); i++ {
         s = a[i]
         anotherFunc(s)
    }
}
// s not accessible here
Despond answered 11/9, 2021 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.