Array/slicing rules

polaris · · 442 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Why does this compile:</p> <pre><code>s := sha1.Sum(b) a = append(a, sum[:]...) </code></pre> <p>but this doesn&#39;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="">addressable</a> if it&#39;s &#34;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. &#34;</p> <p>The return value from Sum is not any of these things. It&#39;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&#39;t slice into arrays until they are actually allocated storage in a function. As in, it isn&#39;t a literal. Strange behavior. </p> <p><a href="" rel="nofollow">It is defined and known by the golang team</a>, so its &#34;operating as expected&#34; so to speak. </p></pre>MindyBraunghSmith: <pre><p>Don&#39;t guess. Read the spec! </p></pre>
442 次点击  
加入收藏 微博
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传