<p>Hi gophers,</p>
<p>The documentation for some of the fasthttp functions, such as <a href="https://godoc.org/github.com/valyala/fasthttp#RequestHeader.Peek" rel="nofollow">https://godoc.org/github.com/valyala/fasthttp#RequestHeader.Peek</a> states something like:</p>
<pre><code>func (h *RequestHeader) Peek(key string) []byte
</code></pre>
<blockquote>
<p>Peek returns header value for the given key.</p>
<p>Returned value is valid until the next call to RequestHeader.
Do not store references to returned value.
Make copies instead.</p>
</blockquote>
<p>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?</p>
<hr/>**评论:**<br/><br/>Deathknife: <pre><p>[]byte is a slice rather than an array. As a slice, it acts as a "pointer".</p>
<p><a href="https://blog.golang.org/go-slices-usage-and-internals" rel="nofollow">https://blog.golang.org/go-slices-usage-and-internals</a></p></pre>natbobc: <pre><p>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.</p></pre>Badu_Ro: <pre><p>Look at the noCopy struct <a href="https://github.com/valyala/fasthttp/blob/master/nocopy.go#L7:6" rel="nofollow">https://github.com/valyala/fasthttp/blob/master/nocopy.go#L7:6</a> which points to <a href="https://github.com/golang/go/issues/8005#issuecomment-190753527" rel="nofollow">https://github.com/golang/go/issues/8005#issuecomment-190753527</a>
By the way, that is not a beginner question.</p></pre>
beginner question about valyala/fasthttp warning me to copy not reference a returned value
blov · · 475 次点击这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传