相比起c++,golang的变量赋值,初始化种类都要多
c++:
//变量类型 变量名 = 初始值
int temp=32;
go的方式就很多了(想必你们会发现这里没有c++的分号了,是的,go语言不需要在换行时加分号,系统会自动加上):
//以下四种表达是等价的
s := ""
var s string
var s = ""
var s string = ""
至于这四种的区别,借用《The Go Programming Language》的说法:
“Why should you prefer one form to another? The first form,ashort variable declaration, is the most compact, but it may be used only wit hin a function, not for package-le vel var iables.The second form relies on default initialization to the zero value for strings, which is “”. The third form is rarely used except when declaring multiple variables. The fourth form is explicitab out the variable’s type, which is redundant when it is the same as that of the initial value but necessary in other cas es where the y are not of the same typ e. In practice, you should generally use one of the firs t two for ms, wit h explicit initializat ion to say that the initial value is important and imp licit initializat ion to say that the initial value doesn’t matter.”(中文翻译难以准确,请耐心阅读翻译)
附:各种变量的默认值:
go语言变量声明后的默认值(来自这篇文章)
在go语言中,任何类型在声明后没有赋值的情况下,都对应一个零值。
整形如int8、byte、int16、uint、uintprt等,默认值为0。
浮点类型如float32、float64,默认值为0。
布尔类型bool的默认值为false。
复数类型如complex64、complex128,默认值为0+0i。
字符串string的默认值为”“。
错误类型error的默认值为nil。
对于一些复合类型,如指针、切片、字典、通道、接口,默认值为nil。而数组的默认值要根据其数据类型来确定。例如:var a [4]int,其默认值为[0 0 0 0]。
var a int32 = 100
var a64 int64
a64 = int64(a)
注意:_(下划线)是个特殊的变量名,任何赋予它的值都会被丢弃。(因为go语言编译时会检查没被用到的变量,所以随便定义一个变量来回收没有用的返回值是会报错的(尤其是go支持返回多个返回值,这种情况常常发生))