【问题标题】:Out of bounds when appending in Go slice在 Go 切片中追加时超出范围
【发布时间】:2019-11-05 15:56:14
【问题描述】:

在某些情况下,当 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:]...)
            }
        }
    }
}

【问题讨论】:

    标签: go slice


    【解决方案1】:

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

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

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

    【讨论】:

    • 是的,最终选择了第二个选项。愚蠢的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多