golang:var b Buffer和bytes.Buffer {}之间的区别

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,

:= 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.