<p>I've seen both forms and I was wondering if there was a reason not to go the former.</p>
<hr/>**评论:**<br/><br/>drvd: <pre><p>IMHO the former is more idiomatic , especially as len of a nil slice returns 0 and you can append to a nil slice. Constructing an empty (but non nil slice) probably is overkill. But of course this depends on the contract of the function: If the function must never return a nil slice then you have to use the later. But such a contract seems weird.</p></pre>jewishobo: <pre><p>And that contract is unenforceable by the compiler. <del>If an error is returned the other value is bad, don't use it</del> (see below). </p></pre>SteveMcQwark: <pre><p>This is false. For example, the contract for io.Writer:</p>
<p><a href="https://golang.org/pkg/io/#Writer" rel="nofollow">https://golang.org/pkg/io/#Writer</a></p>
<p>Returning an error does not mean that the other value is invalid.</p></pre>gholtgholt: <pre><p>Possibly a nil return could be interpreted distinctly from a zero-length slice return. Such as "not found" versus "found, but empty". That should be in the doc comment explaining such a small nuance though.</p></pre>weberc2: <pre><p>As far as I know, there is no difference between <code>nil</code> and <code>[]T{}</code>, so the caller would have no means to inspect the return value to distinguish between your "not found" and "found but empty" scenarios.</p></pre>comrade_donkey: <pre><p>There is. []T{} != nil</p></pre>weberc2: <pre><p>Oh, cool. I didn't realize.</p></pre>neoasterisk: <pre><blockquote>
<p>I've seen both forms</p>
</blockquote>
<p>Where have you seen <code>return []T{}, err</code>? I don't think I have seen it anywhere in the standard library but I might be wrong.</p></pre>: <pre><p>[deleted]</p></pre>Niriel: <pre><p>Actually you can append to a nil slice. In
<a href="https://blog.golang.org/slices" rel="nofollow">https://blog.golang.org/slices</a> we can read</p>
<p>"As should be clear, an empty slice can grow (assuming it has non-zero capacity), but a nil slice has no array to put values in and can never grow to hold even one element.</p>
<p>That said, a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation. As an example, look at the one-liner above that copies a slice by appending to a nil slice [...]."</p></pre>tdewolff: <pre><p>Exactly, by returning nil we avoid the construction of an empty slice and have the benefit that the caller can append nonetheless to the return value, whether there was an error or not. Avoiding slice allocation would be preferred.</p></pre>funny_falcon: <pre><p>there is no <code>nil</code> for <code>string</code>, only <code>""</code></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传