为什么结构体缓冲区不需要初始化?

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

Why struct buffer do not need to initialize

问题

我正在尝试使用Buffer包,并从Buffer文档中复制以下代码。

package main

import (
	"bytes"
	"fmt"
	"os"
)

func main() {
	var b bytes.Buffer // Buffer不需要初始化。
	b.Write([]byte("Hello "))
	fmt.Fprintf(&b, "world!")
	b.WriteTo(os.Stdout)
}

为什么这里的Buffer不需要初始化?

英文:

I am trying to use Buffer package and copy the following code from Buffer documentation.

package main

import (
	"bytes"
	"fmt"
	"os"
)

func main() {
	var b bytes.Buffer // A Buffer needs no initialization.
	b.Write([]byte("Hello "))
	fmt.Fprintf(&b, "world!")
	b.WriteTo(os.Stdout)
}

Why do Buffer here, not to be initialize?

答案1

得分: 4

你可以在这里看到,Buffer只包含一些整数、buf切片和一些数组。它们都不需要初始化,因为Go语言有零值

你可以在这里了解更多关于切片和数组以及它们的工作原理的信息。

英文:

As you can see here Buffer consists just of some ints, the buf slice and some arrays. All of them need no initialization, since go has zero values.

You can read more about slices and arrays and how they work here.

答案2

得分: 2

它已经初始化。当您没有明确初始化一个变量时,Go语言会将其初始化为其零值。这意味着bytes.Buffer的所有内部字段都会被赋值为0,或者对于相关类型来说是类似的值(例如指针的nil值)。

然后,作者们实现了bytes.Buffer,使得所有值都为0成为一个有意义的起始点(这意味着一个空缓冲区),因此程序员在开始使用缓冲区时不需要显式地初始化它。

英文:

It is initialized. When you do not specifically initialize a variable, go will initialize it to its zero value. That means all the internal fields of a bytes.Buffer gets the value 0, or similar for the relevant types (e.g. nil for pointers).

The authors then implemented bytes.Buffer so all values being 0 is a meaningful starting point(It means an empty buffer), so programmers doesn't need to explicitly initialize it in order to start using a Buffer.

答案3

得分: 0

这是因为当你调用Fprintf方法时,隐式地调用了bytes.Buffer.Write方法,根据文档的说明:

> Write将p的内容附加到缓冲区,根据需要扩展缓冲区。

如果你查看源代码,Write方法调用了grow函数:func (b *Buffer) grow(n int) int

这个函数会判断缓冲区是否为空,因为它假设一个空的缓冲区在内部字段上有0值,这实际上是bytes.Buffer结构的默认初始化方式,就像Go语言中的每个结构体一样。

英文:

This due to the fact that when you call the Fprintf method, the bytes.Buffer.Write method is implicitely called, and as per the doc:

> Write appends the contents of p to the buffer, growing the buffer as needed.

If you look at the source code, Write calls the grow function: func (b *Buffer) grow(n int) int.

This function recognizes that the buffer is empty, because it assumes that an empty buffer has 0 values for its internal fields, which is actually how a bytes.Buffer structure is initialized by default, just like every structure in go.

huangapple
  • 本文由 发表于 2014年7月26日 22:56:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/24972290.html
匿名

发表评论

匿名网友

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

确定