移除切片中的元素

Go does not provide any high level functions to remove elements from a slice. I wrote a function that removes given value from a slice in a way that typically suggested here, but it produced quite unexpected result.

package main

import "fmt"

type Area struct {
    Cells [2][]uint8
}
func main() {
    var area1 Area
    area1.Cells[1] = []uint8 {5, 6, 7}

    area2 := area1

    area1.Cells[1] = removeValueFromCell(area1.Cells[1], 6)

    fmt.Println(area1.Cells[1])
    fmt.Println(area2.Cells[1])
}


func removeValueFromCell(cell []uint8, value uint8) []uint8{
    var res = cell
    for i := 0; i < len(cell); i++ {
        if cell[i] == value {
            res = append(cell[:i], cell[i+1:]...)
        }
    }
    return res
}

This program outputs:

[5 7] <- as expected

[5 7 7] <- why not [5 6 7] or [5 7] ?

Slice values are just headers, pointing to a backing array. The slice header only contains the pointer. So when you copy a slice value, the copy will also point to the same backing array. So if you change the backing array via the original slice header, the copy will also observe the changes.

This is what happens in your case. You assign area1 to area2. Cells is an array of slices. So the array will be copied, which contains slice headers, so slice headers will be copied. Sice headers contain pointers to backing arrays, the backing arrays will not be duplicated.

So there is only one backing array holding the [5, 6, 7] elements. Then calling removeValueFromCell(), it will modify this backing array:

Before:
[5, 6, 7]
After:
[5, 7, 7]

Because the element 6 was removed, and the rest of the slice (the elements [7]) were copied in place of the removed element.

And you assign this new slice header (which properly will only include 2 elements) to area1.Cells[1].

But the slice value area2.Cells[1] points to the same backing array, and since you didn't touch this slice value, it sill has length of 3, so it will see all of the backing arrays changed elements: [5, 7, 7].

Also note that your implementation of removeValueFromCell() is faulty, because if the removable element would be listed multiple times in the slice, it would behave incorrectly. The reason for this is because when you remove an element, indices of subsequent elements are shifted (become less by 1), but your loop variable does not account for this. Easiest to handle this is using a downward loop. For details, see How to remove element of struct array in loop in golang.