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

I am new to Go programming language.

I noticed something strange in Go: I thought it used :=and replaces =with Python, but when I use it =in Go, it also works.

What is the difference between :=and =?

+3
source share
4 answers

=- appointment. more about assignment in Go: Assignments

the subtle difference between =and :=is when =used in variable declarations.

The general form for declaring a variable in Go is:

var name type = expression

, . type, = expression , .

:

var x int = 1
var a int
var b, c, d = 3.14, "stackoverflow", true

:= short variable declaration,

name := expression

: := , =

, . , , , :=

:

 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

, := . , "if", "for" "switch", .

:

+6

short tation := var .

:

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)
}

: , :=, .

+2

:= - " " . , .

, .

"" ( )

= var , . value = off , Go ( "", ints 0, - ). , ..

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
+2

= -

:= is a declare-and-initialize construct for new vars (at least one new var) inside a 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
+2
source

Source: https://habr.com/ru/post/1652869/


All Articles