切片的起始位置大于字符串的长度

huangapple go评论124阅读模式
英文:

Slice start position greater than length of the string

问题

以下是代码的翻译结果:

有人知道为什么下面的代码可以正常运行,它访问了字符串长度加一的索引。

import (
    "fmt"
)

func main() {
    fmt.Println("hi"[2:])
}
英文:

Anyone knows why the code below runs without panic, it accesses the index one over the length of the string.

import (
    "fmt"
)

func main() {
    fmt.Println("hi"[2:])
}

答案1

得分: 3

它不会在长度上进行切片,2恰好是长度(等于它)。

对于数组或字符串,如果满足0 <= low <= high <= len(a),则索引处于范围内,否则索引超出范围。

由于你正在对一个字符串进行切片,如果满足以下条件,索引就处于范围内:

0 <= low <= high <= len(a)

这个表达式:

"hi"[2:]

由于缺少上界,它默认为长度,即2,所以它等同于:

"hi"[2:2]

这在规范上是完全有效的,它将得到一个空字符串。如果你将它改为"hi"[3:],那么它将超出范围,并导致编译时错误(因为对常量字符串进行切片可以在编译时检查)。

原因是上界是排除在外的,例如a[0:0]是有效的,并且长度为0,a[0:1]的长度为1,a[0:len(a)]是有效的,并且长度与a相同。

在切片的情况下,下界甚至可以大于切片的长度(但不能超过切片的容量)。更多详情请参考https://stackoverflow.com/questions/33859066/slicing-out-of-bounds-error-in-go/33859638#33859638。

英文:

It does not slices "over" the length, 2 is exactly the length (equals to it).

> For arrays or strings, the indices are in range if 0 &lt;= low &lt;= high &lt;= len(a), otherwise they are out of range.

Since you are slicing a string, indices are in range if:

0 &lt;= low &lt;= high &lt;= len(a)

This expression:

&quot;hi&quot;[2:]

Since the upper bound is missing, it defaults to length, which is 2, so it is equvivalent to:

&quot;hi&quot;[2:2]

This is perfectly valid by the spec, and it will result in an empty string. If you change it to &quot;hi&quot;[3:], then it will be out of range and result in a compile-time error (as slicing a constant string can be checked at compile-time).

Reasoning is that the upper bound is exclusive, e.g. a[0:0] is valid and will be 0-length, a[0:1] will have a length of 1, a[0:len(a)] valid and will have the same length as a.

In case of slices, the lower bound can even be greater than the slice length (but must not exceed the slice capacity). For more details, see https://stackoverflow.com/questions/33859066/slicing-out-of-bounds-error-in-go/33859638#33859638.

huangapple
  • 本文由 发表于 2017年7月25日 17:28:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/45299185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定