英文:
What does := mean in Go?
问题
我正在按照这个教程进行学习,特别是第8个练习:
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
具体来说,:=
是什么意思?寻找Go文档非常困难,具有讽刺意味。
英文:
I'm following this tutorial, specifically exercise 8:
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
Specifically what does the :=
mean? Searching for Go documentation is very hard, ironically.
答案1
得分: 21
A short variable declaration uses the syntax:
短变量声明 = 标识符列表 ":=" 表达式列表。
它是一个简写形式的常规变量声明,带有初始化表达式但没有类型:
英文:
A short variable declaration uses the syntax:
ShortVarDecl = IdentifierList ":=" ExpressionList .
It is a shorthand for a regular variable declaration with initializer expressions but no types:
答案2
得分: 8
继续前往导览的第12页!
英文:
Keep on going to page 12 of the tour!
> A Tour of Go
>
> Short variable declarations
>
> Inside a function, the := short assignment statement can be used in
> place of a var declaration with implicit type.
>
> (Outside a function, every construct begins with a keyword and the :=
> construct is not available.)
答案3
得分: 7
如其他人已经解释过的那样,:= 用于声明和赋值,而 = 仅用于赋值。
例如,var abc int = 20 与 abc := 20 是相同的。
当你不想在代码中填充类型或结构声明时,这是很有用的。
英文:
As others have explained already, := is for both declaration, and assignment, whereas = is for assignment only.
For example, var abc int = 20 is the same as abc := 20.
It's useful when you don't want to fill up your code with type or struct declarations.
答案4
得分: 5
:=
语法是声明和初始化变量的简写形式,例如 f := "car"
是 var f string = "car"
的简写形式。
短变量声明运算符(:=
) 只能用于声明局部变量。如果你尝试使用短声明运算符声明全局变量,会得到一个错误。
请参考官方文档了解更多详情。
英文:
The :=
syntax is shorthand for declaring and initializing a variable, example f := "car"
is the short form of var f string = "car"
The short variable declaration operator(:=
) can only be used for declaring local variables. If you try to declare a global variable using the short declaration operator, you will get an error.
Refer official documentation for more details
答案5
得分: 1
:= 不是一个运算符,它是短变量声明子句语法的一部分。
更多信息请参考:https://golang.org/ref/spec#Short_variable_declarations
英文:
:= is not an operator. It is a part of the syntax of the Short variable declarations clause.
more on this: https://golang.org/ref/spec#Short_variable_declarations
答案6
得分: 0
根据我在Go语言书上的介绍,这只是一个简短的变量声明语句,与以下代码完全相同:
var s = ""
但是它更容易声明,并且其作用域更小。使用 := 进行变量声明也不能使用 interface{} 类型。尽管如此,这可能是你在几年后才会遇到的问题。
英文:
According to my book on Go, it is just a short variable declaration statement
exactly the same as
var s = ""
But it is more easy to declare, and the scope of it is less expansive. A := var decleration also can't have a type of interface{}. This is something that you will probably run into years later though
答案7
得分: -2
:= 表示一个变量,我们可以使用 := 给变量赋值。
英文:
:= represents a variable, we can assign a value to a variable using :=.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论