英文:
Why use '=' instead of ':='?
问题
//Insert
stmt, err := db.Prepare("INSERT userinfo SET username=?")
// Update
stmt, err = db.Prepare("update userinfo set username=?")
为什么在Insert
中我们使用:=
,而在Update
中我们使用=
?在我看来,两者都应该使用:=
。
英文:
I am looking at the sample code for Go-SQL-Driver
here:
//Insert
stmt, err := db.Prepare("INSERT userinfo SET username=?")
// Update
stmt, err = db.Prepare("update userinfo set username=?")
Why in Insert
we use :=
but in Update
we use =
? It seems to me that both should be :=
答案1
得分: 9
:=
在 短变量声明 中使用;它既声明了左侧的变量,又对它们进行赋值。(这在《Go编程语言规范》的“短变量声明”部分中有解释。)
相比之下,=
只是执行赋值操作。
在你的例子中,第二行使用了 =
,因为变量已经被第一行声明了,所以不需要使用 :=
。(实际上,它会报错::=
只允许在至少有一个变量是“新的”,即尚未声明的情况下使用。)
英文:
:=
is used in a short variable declaration; it both declares the variables on the left-hand-side, and assigns to them. (This is explained in the "Short variable declarations" section of The Go Programming Language Specification.)
=
, by contrast, merely performs assignments.
In your example, the second line uses =
because the variables have already been declared (by the first line), so :=
is not needed. (In fact, it will give an error message: :=
is only allowed when at least one of the variables is "new", i.e., not already declared.)
答案2
得分: 5
=
是赋值运算符之一。
:=
是短变量声明。
在参考链接中,你可以发现语义上有很大的不同,所以实际上“代替”的概念有点问题。
一个可能有帮助的记忆规则:
identifierI := expressionE
等同于
var identifierI = expressionE
等同于
var identifierI typeOf(expressionE)
identifierI = expressionE
英文:
=
is one of the assignement operators.
:=
is the short variable declaration.
In the referenced links you can find that the semantics is quite different, so actually the concept "instead of" is a bit problematic.
A perhaps helpful mnemotechnic rule:
identifierI := expressionE
is the same as
var identifierI = expressionE
which is the same as
var identifierI typeOf(expressionE)
identifierI = expressionE
答案3
得分: 0
:=
是为了方便。重要的区别在于:=
进行类型推断,因此在声明和赋值变量的同时,变量的类型是从函数返回值的类型中推断出来的。
这使得你的程序在大多数情况下更容易阅读,但也意味着某人必须查阅文档来确定函数的返回值类型以了解变量的类型。
当你重新赋值给一个已存在的变量或者在函数内部将值赋给全局/包变量时,你应该使用=
,否则,你将创建一个新的局部变量。
英文:
:=
is for convenience. The important difference is that the :=
does type inference, so as it declares and assigns the variable all one line, the variables type is inferred from the return value's type of the function.
This makes your program easier to read in most cases but does mean someone will have to look up in the docs the function's return value type to figure out the variable's type.
You'll want to use =
when you're re-assiging to an existing variable or when assigning to a global/package variable from within a function, otherwise, you'll be creating a new local variable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论