Go 中的 := 和 = 有什么区别?

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

我是 Go 编程语言的新手。

我注意到 Go 中有一些奇怪的东西:我认为它使用 := 并在 Python 中替换 =,但是当我在 Go 中使用 = 时它也是作品。

:==有什么区别?

在函数内部,:= 短赋值语句可用于代替具有隐式类型的 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)
}

注意::=声明的变量只能在函数块内部使用。

:= 是声明和初始化变量的 "short declaration form"。它会对您分配的值进行类型推断以设置变量的类型。

如果您试图用短声明形式对同一范围内的同一变量进行赋值,编译器将抛出错误。

注意短声明形式"shadowing"封闭范围内的相同变量(尤其是有错误的)

= 在声明变量时需要 var 关键字,并且变量的类型明确跟在变量名称之后。实际上你可以把 = 从声明中去掉,因为 Go 对所有类型都有一个初始值(字符串初始化为“”,整数为 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

= 只是赋值

:= 是函数块(非全局)内新变量(至少一个新变量)的声明和初始化构造:

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

= 是赋值。关于 Go 中赋值的更多信息:Assignments

=:= 之间的细微差别是在变量声明中使用 = 的时候。

Go 中变量声明的一般形式是:

var name type = expression

上面的声明创建了一个特定类型的变量,为其附加了一个名称,并设置了它的初始值。 type= expression 可以省略,但不能同时省略。

例如:

var x int = 1
var a int
var b, c, d = 3.14, "Whosebug", 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”语句的初始值设定项,它们可用于声明局部临时变量。

更多信息:

variable declarations

short variable declarations

我花了一些时间找出我犯的一个错误,它可以帮助您弄清 :== 之间的区别。 考虑以下代码:

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

}

= 用作静态类型。

:= 用作动态类型。

示例:

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

b := 40      # dynamically checked. 

请注意 :==range 子句中的区别。以下示例改编自 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

在 Go 中声明变量的最冗长的方式是使用 var 关键字、显式类型和赋值。

var x int = 10

Go 还支持短声明格式。当你在一个函数中时,你可以 使用 := 运算符替换使用类型推断的 var 声明。

var x = 10
x := 10

:= 有一项限制。如果你在包级别声明一个变量,你 必须使用 var 因为 := 在函数之外是不合法的。

函数中有些情况你应该避免:=

  • 将变量初始化为其零值时,使用 var x int。这很清楚 零值是有意的。
  • 将无类型常量或文字分配给变量和默认类型时 对于常量或文字不是您想要的变量类型,请使用 long var 具有指定类型的表单。虽然使用类型转换来指定是合法的 值的类型,用:=写成x := byte(20),这是惯用的写法 var x byte = 20.
  • 因为 := 允许您对新变量和现有变量进行赋值,有时 当您认为您正在重用现有变量时创建新变量。在那些情况下,显式声明所有 你的新变量用 var 来明确哪些变量是新的,然后 使用赋值运算符 (=) 为新旧变量赋值。

虽然 var 和 := 允许您在同一行上声明多个变量,但仅使用 分配从函数返回的多个值时的这种样式或逗号 ok 成语.

学习 Go 乔恩·邦德纳