beginner question about valyala/fasthttp warning me to copy not reference a returned value

blov · 2018-01-26 15:30:03 · 633 次点击    
这是一个分享于 2018-01-26 15:30:03 的资源,其中的信息可能已经有所发展或是发生改变。

Hi gophers,

The documentation for some of the fasthttp functions, such as https://godoc.org/github.com/valyala/fasthttp#RequestHeader.Peek states something like:

func (h *RequestHeader) Peek(key string) []byte

Peek returns header value for the given key.

Returned value is valid until the next call to RequestHeader. Do not store references to returned value. Make copies instead.

I just don't quite grok why this warning exists - surely the []byte array returned by this function is passed by value, not by reference?


评论:

Deathknife:

[]byte is a slice rather than an array. As a slice, it acts as a "pointer".

https://blog.golang.org/go-slices-usage-and-internals

natbobc:

They avoid GC by using memory pools and that's the guarantee they provide. As @Deathknife mentioned the underlying data/array isn't a mem copy, only the "shell" which basically includes the len, capacity, and a pointer to the array.

Badu_Ro:

Look at the noCopy struct https://github.com/valyala/fasthttp/blob/master/nocopy.go#L7:6 which points to https://github.com/golang/go/issues/8005#issuecomment-190753527 By the way, that is not a beginner question.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

633 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传