Search code examples
arraysgoslice

How can I replace part of a slice with another in go


I would like to see if there is a simple way to replace a portion of a slice with all the values of another slice. For instance:

x := []int{1,2,0,0}
y := []int{3,4}

// goal is x == {1,2,3,4}

x[2:] = y    // compile error
x[2:] = y[:] // compile error

I know that I can always iterate through through y, but Go has a bunch of cool features and I'm pretty new to Go. So perhaps I'm going about this the wrong way.


Solution

  • You can use the builtin copy:

    The copy built-in function copies elements from a source slice into a destination slice.

    package main
    
    import "fmt"
    
    func main() {
        x := []int{1, 2, 0, 0}
        y := []int{3, 4}
    
        copy(x[2:], y)
    
        fmt.Println(x) // [1 2 3 4]
    }
    

    Stealing from the above comment, you can learn more on slices here:

    I also found this blog post informative: https://divan.dev/posts/avoid_gotchas/#arrays-and-slices