<p>Why does this compile:</p>
<pre><code>s := sha1.Sum(b)
a = append(a, sum[:]...)
</code></pre>
<p>but this doesn't, failing with <code>invalid operation sha1.Sum(b)[:] (slice of unaddressable value)</code>:</p>
<pre><code>a = append(a, sha1.Sum(b)[:]...)
</code></pre>
<hr/>**评论:**<br/><br/>moinboin: <pre><p>The specification states that the slice expression operand must be addressable. An operand is <a href="https://golang.org/ref/spec#Address_operators">addressable</a> if it's "either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. "</p>
<p>The return value from Sum is not any of these things. It's not addressable and therefore cannot be used as a slice operand.</p></pre>ergotayours: <pre><p>I see. In C++-speak, addressable would basically mean an lvalue, right?</p></pre>MindyBraunghSmith: <pre><p>Yes, they are similar.</p></pre>ergotayours: <pre><p>Cool, thanks for the help!</p></pre>010a: <pre><p>My guess is that it has something to do with the fact that <code>sha1.Sum()</code> returns <code>[Size]byte</code>, not just <code>[]byte</code>. <code>[Size]byte</code> is an array, whereas <code>[]byte</code> is a slice. </p>
<p>You can distill the problem down:</p>
<pre><code>a := []int{1,2,3}[:] // works
b := [3]int{1,2,3}[:] // compile error
b := [3]int{1,2,3} // works
c := b[:] // works
</code></pre>
<p>Clearly it has something to do such that you can't slice into arrays until they are actually allocated storage in a function. As in, it isn't a literal. Strange behavior. </p>
<p><a href="https://github.com/golang/go/blob/21ec72c2ca5168f3f10b4594a553b3a038c8df29/test/complit1.go" rel="nofollow">It is defined and known by the golang team</a>, so its "operating as expected" so to speak. </p></pre>MindyBraunghSmith: <pre><p>Don't guess. Read the spec! </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传