<p>I would like know why "s[1:]" in the 2nd fmt.Println isn't throwing an index out of range error? Index 1 is clearly out of range</p>
<p>package main</p>
<p>import "fmt"</p>
<p>func main() {</p>
<p>s := "J"</p>
<p>//fmt.Println(s[1]) // This results in a runtime error: index out of range</p>
<p>fmt.Println(s[1:]) // Why does this work? Index value 1 is clearly out of range, but the statement prints an empty string</p>
<p>}</p>
<hr/>**评论:**<br/><br/>DeedleFake: <pre><p>The Python docs explain it best, I think. You can think of indices in a slice as being <em>between</em> elements. For example, given the string "example":</p>
<pre><code> e x a m p l e
0|1|2|3|4|5|6|7
</code></pre>
<p>If you only have one element, there are two slice indices: One before the element and one after it.</p></pre>tdewolff: <pre><p>This exactly, well put.</p>
<p>Additionally, combined with open ending as Go has, it's very convenient for various string manipulations, as gohacker mentioned.</p></pre>jasongu79: <pre><p>Very interesting; never knew about this, thanks!</p></pre>Fwippy: <pre><p>Previous discussion on this topic: <a href="https://www.reddit.com/r/golang/comments/3kmxyc/wait_so_why_doesnt_this_panic/" rel="nofollow">https://www.reddit.com/r/golang/comments/3kmxyc/wait_so_why_doesnt_this_panic/</a></p></pre>gohacker: <pre><p>So that you can write <code>a = append(a[:i], a[i+1:]...)</code>.</p></pre>jasongu79: <pre><p>Can you elaborate on why allowing index to be len(str) has to do with append(a[:i], a[i+1:]...)?</p></pre>pdq: <pre><p>I can't explain the rationale, but len(slice) being legal is documented as part of the spec. I am in agreement with you that the max allowed <em>should</em> be len(slice)-1.</p>
<p><a href="https://golang.org/ref/spec#Slice_expressions" rel="nofollow">https://golang.org/ref/spec#Slice_expressions</a></p>
<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. A constant index must be non-negative and representable by a value of type int; for arrays or constant strings, constant indices must also be in range. If both indices are constant, they must satisfy low <= high. If the indices are out of range at run time, a run-time panic occurs."</p></pre>jasongu79: <pre><p>I read the spec, but like you, I'm not sure about the rationale to allow the lower index to be len(str), instead of len(str)-1</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传