问题描述
我是Go编程语言的新手。我在Go中发现了一些奇怪的东西:我认为它使用了
:= 和 = ?
= 是赋值。更多关于Go的分配:
当 = 时, = 和:= 之间的细微区别>在变量声明中使用。
Go中的变量声明的一般形式为:
var name type = expression
上面的声明创建了一个特定类型的变量,一个名称,并设置其初始值。 类型或 =表达式都可以省略,但不能同时存在。
例如:
var x int = 1
var a int
var b,c,d = 3.14,stackoverflow,true
:= 被称为短变量声明其形式为
name:=表达式
并且名称的类型由表达式类型
请注意: := 是一个声明,而 = 是一项任务
所以,一个简短的变量声明必须至少声明至少一个新变量。这意味着一个简短的变量声明不一定会在其左侧声明所有的变量,当它们中的一些已经被声明在同一个词法块中时,那么:= 就像对这些变量赋值一样
例如:
r := foo()// ok,声明一个新变量r
r,m:= bar()// ok,声明一个新变量m并赋值ra新值
r,m:= bar2() //编译错误:无新变量
另外,:= 可能只出现在函数内部。在某些情况下,例如if,for或switch语句的初始值设定项,它们可用于声明本地临时变量。
更多信息:
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 =?
= is assignment. more about assignment in Go: Assignments
the subtly 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:
这篇关于Go和Go =的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!