<pre><code>package main
import "fmt"
func main() {
v := []int{1,2,3,4,5,6}
fmt.Println(len(v))
v = v[:len(v)-1]
for i:= 0; i <100000000; i+=1{
v[0],v[1]=v[1],v[0]
}
v = v[:len(v)+1] // Safe?
fmt.Println(v[len(v)-1])
}
</code></pre>
<hr/>**评论:**<br/><br/>adonovan76: <pre><p>The behavior of this program is completely determined by the spec, so it's safe in that respect. But your job might not be safe if you write code like this. :)</p>
<p>The loop is a no-op, since it swaps the first two elements an even number of times.</p>
<p>Expanding a slice <code>v[:n]</code> is fine so long as <code>n <= cap(v)</code>; otherwise, it panics.</p></pre>therealdrowranger: <pre><p>The loop was there, as I was testing it the GC reacted. But I see that it doesnt touch it for obvious reasons now.</p></pre>xena-warrior-prince: <pre><p>Probably unsafe (because you don't seem to know why it works).</p>
<p>It works because you're extending the slice to <em>capacity</em> of the slice (the length of underlying array), which in this case happens to have space.</p>
<p><a href="https://golang.org/ref/spec#Slice_expressions">https://golang.org/ref/spec#Slice_expressions</a></p>
<p>relevant bit (but try to read and understand <em>all</em> of it):</p>
<blockquote>
<p>For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. For slices, the upper index bound is the slice capacity cap(a) rather than the length</p>
</blockquote></pre>--Mister--j: <pre><p>I don't know if the programming style is sound. But this works because slices are only wrappers to arrays. Slices have length and capacity which means an array of 10 elements (capacity) might look to a slice as having 5 elements (length).</p>
<p>Program:-
<a href="http://ideone.com/BfA7ft" rel="nofollow">http://ideone.com/BfA7ft</a></p>
<p>Output:-
[1 2 3 4 5]
5 5</p>
<p>Now
[1 2 3 4]
4 5</p>
<p>Now
[1 2 3 4 5]
5 5</p></pre>tdewolff: <pre><p>Besides, you do the same thing over and over again because you don't use the <code>i</code> in your loop. Use a for-range clause:</p>
<pre><code>v := []int{1,2,3,4,5,6}
for i := range v[:len(v)-1] {
v[i], v[i+1] = v[i+1], v[i]
}
</code></pre>
<p>What do you want to do? Bubble sort?</p></pre>therealdrowranger: <pre><p>Sorry about that. At the time, I was giving the GC time to react. I know now that is nonsense.</p></pre>tschottdorf: <pre><p>this is safe (but of course funky code).
Your <code>v</code> has capacity 5, so <code>v[:5]</code> and below is ok (unless you do something with the slice that could change its capacity).</p></pre>: <pre><p>[removed]</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传