Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing elements in a slice

Tags:

arrays

slice

go

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] ?
like image 998
sax Avatar asked Aug 30 '18 09:08

sax


People also ask

How do you delete an element from a slice?

Items need to be removed from a slice by slicing them out. To remove an element, you must slice out the items before that element, slice out the items after that element, then append these two new slices together without the element that you wanted to remove.

How do you add elements to a slice?

To add an element to a slice , you can use Golang's built-in append method. append adds elements from the end of the slice. The first parameter to the append method is a slice of type T . Any additional parameters are taken as the values to add to the given slice .

What is cap in Slice?

In Go, there are two functions that can be used to return the length and capacity of a slice: len() function - returns the length of the slice (the number of elements in the slice) cap() function - returns the capacity of the slice (the number of elements the slice can grow or shrink to)


1 Answers

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. Slice 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 still has the 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.

like image 190
icza Avatar answered Nov 15 '22 03:11

icza