gpt4 book ai didi

golang : difference between var b Buffer and bytes. 缓冲区{}

转载 作者:IT王子 更新时间:2023-10-29 01:07:06 26 4
gpt4 key购买 nike

var b bytes.Buffer // A Buffer needs no initialization.


b := bytes.Buffer{}

这两个有什么区别?我在这里试过:http://play.golang.org/p/lnkkULeIYm没看出区别。谢谢,

最佳答案

:=var 的简写语法,在这种情况下 b 是一个零值 bytes.Buffer

var b bytes.Buffer // is the same as
var b = bytes.Buffer{} // is the same as
b := bytes.Buffer{}

您不能在函数外使用简写版本,因此对于全局变量,您必须使用 var

来自 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.

关于golang : difference between var b Buffer and bytes. 缓冲区{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25519225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com