英文:
NewBuffer([]bytes,int,int64) method not found in go lang bytes package
问题
我是你的中文翻译助手,以下是翻译好的内容:
我是Go语言的新手。我正在尝试理解ioutil中的ReadAll(r Reader, capacity int64)方法内部发生了什么。在这个方法内部,有一行代码:
buf := bytes.NewBuffer(make([]byte, 0, capacity))
但是问题是,在bytes包中只有一个参数的NewBuffer方法,如下所示:
func NewBuffer(buf []byte) *Buffer
我一遍又一遍地搜索bytes包的文档,但找不到带有3个参数的NewBuffer方法。
那么实际上,NewBuffer(make([]byte, int, int64))方法是从哪里调用的呢?
英文:
I'm new in go language. I'm trying to understand what's happening inside ioutil.ReadAll(r Reader, capacity int64) method. Inside this method there is a line like:
buf := bytes.NewBuffer(make([]byte, 0, capacity))
But the problem is inside bytes package there is a NewBuffer method with only parameter like:
func NewBuffer(buf []byte) *Buffer
I searched bytes package documentation again and again but can't find NewBuffer method with 3 parameter.
So actually from where NewBuffer(make([]byte, int, int64)) method calling?
答案1
得分: 4
make([]byte, 0, capacity)
返回一个新的字节切片([]byte
),其长度为0,容量为capacity
。
换句话说,将其分成多行可能有助于你理解:
capacity := 100 // 或其他值
var myBytes []byte = make([]byte, 0, capacity)
buf := bytes.NewBuffer(myBytes)
英文:
make([]byte, 0, capacity)
returns a new byte slice ([]byte
) initialized to length 0 and capacity capacity
.
In other words, it might help you to see it on multiple lines:
capacity := 100 // or whatever
var myBytes []byte = make([]byte, 0, capacity)
buf := bytes.NewBuffer(myBytes)
答案2
得分: 2
你忽略了一个事实,那就是你正在使用一个参数调用bytes.NewBuffer()
函数,而这个参数恰好是一个方法调用——make([]byte, 0, capacity)
,它返回一个字节切片。
英文:
Youre missing the fact that you're calling the bytes.NewBuffer()
function with a single parameter, which happens to be a method call - make([]byte, 0, capacity)
- which returns an byte slice.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论