如何转到切片中的下一项

我已经编写了以下代码来获取数组中的下一项。


count:=len(value.Values)

for index, currentRow := range value.Values {

    var nextRow Value

    if index< count{

    nextRow = value.Values[index+1]

    fmt.Print(nextRow)

    }

}

我在运行上述代码时感到恐慌。


Goroutine panic: 运行时错误: 索引超出范围


任何关于如何从切片中获取下一项的想法。


绝地无双
浏览 112回答 1
1回答

慕码人2483693

下一项确实是 ,但如果是最后一个元素的索引,则没有下一项,在这种情况下是无效的索引,并且尝试使用它会导致运行时死机。value.Values[index+1]indexindex+1value.Values所以检查索引:for index, currentRow := range value.Values {&nbsp; &nbsp; var nextRow Value&nbsp; &nbsp; if index < timeSeriesDataCount && index < len(value.Values)-1 {&nbsp; &nbsp; &nbsp; &nbsp; nextRow = value.Values[index+1]&nbsp; &nbsp; &nbsp; &nbsp; fmt.Print(nextRow)&nbsp; &nbsp; }}另一种选择是在一个少一个切片上划一个范围(不包括最后一个元素),因此无需检查 ,肯定还有另一个元素:indexfor index, currentRow := range value.Values[:len(value.Values)-1] {&nbsp; &nbsp; var nextRow Value&nbsp; &nbsp; if index < timeSeriesDataCount {&nbsp; &nbsp; &nbsp; &nbsp; nextRow = value.Values[index+1]&nbsp; &nbsp; &nbsp; &nbsp; fmt.Print(nextRow)&nbsp; &nbsp; }}在这种情况下,您必须考虑的是,如果是空的,因为如果是,则上述切片操作将再次惊慌失措,因此请检查:value.Valuesif len(value.Values) > 0 {&nbsp; &nbsp; for index, currentRow := range value.Values[:len(value.Values)-1] {&nbsp; &nbsp; &nbsp; &nbsp; var nextRow Value&nbsp; &nbsp; &nbsp; &nbsp; if index < timeSeriesDataCount {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nextRow = value.Values[index+1]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Print(nextRow)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}请注意,我们可以检查是否,因为即使不会有恐慌,如果,也会有迭代。len(value.Values) > 1len = 10另请注意,在排除最后一个元素的切片上进行范围不会访问最后一个元素(显然),因此,如果您要对元素执行任何其他操作,这可能不可行,但在您的示例中,它们是等效的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go