登录
首页 >  Golang >  Go问答

Go切片中追加元素时超出索引范围

来源:stackoverflow

时间:2024-03-24 14:51:34 404浏览 收藏

当 Go 切片中的索引达到切片长度时,追加元素会导致切片越界错误。在 `filterIntersection` 函数中,当切片元素在遍历期间被移除时,索引可能超出范围。例如,当 `i == len(sliceA)` 时,`sliceA[i+1]` 会越界。

问题内容

在某些情况下,当 i == len(slicea) 时,我会收到切片越界错误。

//filterIntersection removes points from two slices that have common points.
func filterIntersection(sliceA, sliceB *[]ds.Coord) {
    for i, a := range *sliceA {
        for j, b := range *sliceB {
            if a == b {
                (*sliceA) = append((*sliceA)[:i], (*sliceA)[i+1:]...) <--- error here
                (*sliceB) = append((*sliceB)[:j], (*sliceB)[j+1:]...)
            }
        }
    }
}

解决方案


如果 i == len(SliceA),则 sliceA[i+1] 出界!这不是“在某些情况下”,而是在所有情况下,SliceB 也会发生同样的情况。

如果 i == len(SliceA)j == len(SliceB),请考虑跳出循环。

另一个解决方案是使用“常规”for 循环: for i := 0;我 < len(SliceA); i++

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Go切片中追加元素时超出索引范围》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>