golang: var b Buffer 和 bytes.Buffer{} 之间的区别是什么?

huangapple go评论83阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年8月27日 13:03:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/25519225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定