Go和Go =的区别是什么? [英] What is the difference between := and = in Go?

查看:188
本文介绍了Go和Go =的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Go编程语言的新手。

我在Go中发现了一些奇怪的东西:我认为它使用了:= ,并用 = 在Python中,但是当我在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:

variable declarations

short variable declarations

这篇关于Go和Go =的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆