7

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.

1

2 Answers 2

15

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

1
  • 2
    Thanks miku! That worked perfectly. Also, the play.golang.org link was really cool.
    – caffein
    Mar 10, 2020 at 20:22
1

There is one Replace function in x/exp/slices:

Replace replaces the elements s[i:j] by the given v, and returns the modified slice. Replace panics if s[i:j] is not a valid slice of s.

import (
    "fmt"
    "golang.org/x/exp/slices"
)

func main() {
    x := []int{1, 2, 0, 0}
    y := []int{3, 4}
    z := slices.Replace(x, 2, 4, y...)
    fmt.Println(z)
}

Playground

2
  • 1
    watch out that currently Replace has a bug by which it doesn't panic on invalid i and j values, but instead returns a corrupted slice. issue.
    – blackgreen
    Nov 11, 2022 at 20:04
  • Wow, @blackgreen, thank you very much for your information. This issue is resolved for now.
    – zangw
    Nov 12, 2022 at 1:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.