英文:
golang: difference between var b Buffer and bytes.Buffer{}
问题
这两者之间有什么区别?
我在这里尝试了一下:http://play.golang.org/p/lnkkULeIYm
没有看到区别。
谢谢。
英文:
var b bytes.Buffer // A Buffer needs no initialization.
b := bytes.Buffer{}
What is the difference between these 2?
I tried here: http://play.golang.org/p/lnkkULeIYm
didn't see difference.
Thanks,
答案1
得分: 3
:=
是 var
的简写语法,在这种情况下,b 是一个零值的 bytes.Buffer
。
var b bytes.Buffer // 等同于
var b = bytes.Buffer{} // 等同于
b := bytes.Buffer{}
在函数外部无法使用简写版本,所以对于全局变量,你必须使用 var
。
根据 http://tip.golang.org/ref/spec#Short_variable_declarations:
与常规变量声明不同,短变量声明可以重新声明变量,前提是它们在同一块中以相同的类型进行了原始声明,并且至少有一个非空白变量是新的。
因此,重新声明只能出现在多变量的短声明中。重新声明不会引入新变量;它只是给原始变量赋予一个新值。
英文:
:=
is the shorthand syntax of var
, in that case b is a zero-valued bytes.Buffer
.
var b bytes.Buffer // is the same as
var b = bytes.Buffer{} // is the same as
b := bytes.Buffer{}
You can't use the short hand version outside functions, so for a global variable you have to use var
.
From http://tip.golang.org/ref/spec#Short_variable_declarations:
> Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new.
>
> As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论