英文:
What is the difference between := and = in Go?
问题
:=
和 =
在 Go 语言中有不同的用法。
:=
是用于声明并初始化一个新的变量。它可以根据右侧的表达式的类型自动推断出变量的类型,并将其赋值给变量。这种方式被称为短变量声明。
例如:
name := "John"
age := 25
=
是用于将一个值赋给一个已经存在的变量。它不会创建新的变量,只是将右侧的值赋给左侧的变量。
例如:
name = "Jane"
age = 30
所以,:=
和 =
在 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 =
?
答案1
得分: 78
=
是赋值操作符。关于 Go 中的赋值操作可以参考:赋值操作
=
和 :=
的微妙区别在于变量声明时使用的情况。
Go 中变量声明的一般形式是:
var 变量名 类型 = 表达式
上述声明创建了一个特定类型的变量,给它附上一个名称,并设置其初始值。类型
和 = 表达式
中的一个可以省略,但不能同时省略。
例如:
var x int = 1
var a int
var b, c, d = 3.14, "stackoverflow", true
:=
被称为 短变量声明
,其形式为
变量名 := 表达式
并且变量名的类型由表达式的类型确定。
请注意::=
是一个声明,而 =
是一个赋值操作
因此,短变量声明必须至少声明一个新变量。这意味着短变量声明不一定要声明左侧所有的变量,当其中一些变量在同一词法块中已经声明时,:=
就像对这些变量进行赋值一样。
例如:
r := foo() // 可行,声明一个新变量 r
r, m := bar() // 可行,声明一个新变量 m,并给 r 赋一个新值
r, m := bar2() // 编译错误:没有新变量
此外,:=
只能出现在函数内部。在某些上下文中,比如 "if"、"for" 或 "switch" 语句的初始化器中,它们可以用于声明局部临时变量。
更多信息:
英文:
=
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:
答案2
得分: 11
=
只是赋值操作符。
:=
是在函数块内部声明和初始化新变量(至少一个新变量)的构造方式(不是全局的):
var u1 uint32 //声明一个变量并初始化为0
u1 = 32 //赋值
var u2 uint32 = 32 //声明一个变量并立即赋值
//使用定义数据类型声明一个新变量:
u3 := uint32(32) //在函数块内部,这等同于:var u3 uint32 = 32
fmt.Println(u1, u2, u3) //32 32 32
//u3 := 20//错误::= 左边没有新变量
u3 = 20
fmt.Println(u1, u2, u3) //32 32 20
u3, str4 := 100, "str" // 至少有一个新变量
fmt.Println(u1, u2, u3, str4) //32 32 100 str
以上是要翻译的内容。
英文:
=
is just assignment
:=
is declare-and-initialize construct for new vars (at least one new var) inside the function block (not global):
<!-- language: lang-golang -->
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
答案3
得分: 5
":=" 是用于声明和初始化变量的“短声明形式”。它会对你赋值的值进行类型推断,以设置变量的类型。
如果你尝试在同一作用域内使用短声明形式对同一变量进行赋值,编译器会报错。
要注意短声明形式可能会在封闭作用域中“遮蔽”同一变量(尤其是在出现错误时)。
"=" 在声明变量时需要使用 var 关键字,并在变量名后明确指定变量的类型。实际上,你可以省略声明中的 "=",因为 Go 语言对所有类型都有初始值(字符串初始化为空字符串,整数初始化为 0,切片初始化为空切片)。它还可以用于只使用一个值进行重新赋值,例如:
var s string = "a string" // 声明并初始化为 "a string"
s = "something else" // 重新赋值
var n int // 声明并初始化为 0
n = 3
英文:
:=
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
答案4
得分: 3
在函数内部,可以使用:=
短赋值语句来代替具有隐式类型的变量声明。
例如:
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)
}
**注意:**使用:=
声明的变量只能在函数块内部使用。
英文:
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.
答案5
得分: 2
在Go语言中,声明变量最冗长的方式是使用var
关键字、显式类型和赋值语句。
var x int = 10
Go语言还支持一种简短的声明格式。在函数内部,可以使用:=
运算符来替代使用类型推断的var
声明。
var x = 10
x := 10
对于:=
有一个限制。如果在包级别声明变量,必须使用var
,因为在函数外部使用:=
是不合法的。
在函数内部的某些情况下,应避免使用:=
:
- 当将变量初始化为其零值时,使用
var x int
。这样可以清楚地表明零值的意图。 - 当将无类型常量或字面量赋值给变量,并且常量或字面量的默认类型与变量所需类型不同时,使用带有指定类型的长形式
var
。虽然可以使用类型转换来指定值的类型并使用:=
写作x := byte(20)
,但习惯上应写作var x byte = 20
。 - 因为
:=
允许同时对新变量和现有变量进行赋值,所以有时在你认为正在重用现有变量时,它会创建新变量。在这些情况下,使用var
显式声明所有新变量,以明确哪些变量是新变量,然后使用赋值运算符(=)
为新变量和旧变量赋值。
虽然var
和:=
允许在同一行上声明多个变量,但只有在从函数返回多个值或使用逗号ok习惯用法时才使用这种风格。
《学习Go语言 Jon Bondner》
英文:
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 writex := byte(20)
, it is idiomatic to write
varx 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 withvar
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
答案6
得分: 1
我花了一些时间找出了一个错误,这个错误可以帮助你澄清:=
和=
之间的区别。
考虑以下代码:
type mystruct struct {
a int
arr []int
}
func main() {
m := mystruct{}
m.arr := make([]int, 5) //编译错误,因为m.arr已经声明过了。
m.arr = make([]int, 5) //编译通过
}
英文:
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
}
答案7
得分: 0
= 用于静态类型。
:= 用于动态类型。
示例:
var a = 30 # 静态类型,编译时检查
b := 40 # 动态检查
英文:
= 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.
答案8
得分: 0
请注意:=
和=
在range
子句中的区别。以下示例摘自规范。
= range ...
:
i := 2
x = []int{3, 5, 7}
for i, x[i] = range x { // i,x[2] = 0,x[0]
break
}
// 现在 i == 0,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 == 迭代中遇到的最后一个映射键(注意映射迭代的顺序是随机的)
// val == map[key]
:= range ...
:
var a [10]string
for i, s := range a {
// i 的类型是 int,s 的类型是 string
// s == a[i]
someFunction(i, s)
}
// i 和 s 在此处不再可访问。
for i := range a { // 大致等同于 `for i := 0; i < len(a); i++`
someFunction(i, a[i])
}
for _, s := range a {
anotherFunc(s)
}
// 上述代码大致等同于:
{
var s string
for i := 0; i < len(a); i++ {
s = a[i]
anotherFunc(s)
}
}
// s 在此处不可访问
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论