Saturday, May 11, 2024
HomeGolangCopy a slice in Go (Golang)

Copy a slice in Go (Golang)



To duplicate a slice in Go, getting a deep copy of its contents, you want to both use the built-in copy() operate, or create a brand new empty slice and add all the weather of the primary slice to it utilizing the append() operate. Due to how slices are inbuilt Go, assigning one slice to a different solely makes a shallow copy, and you shouldn’t use it if you wish to clone the slice in a deep method.

Copy a slice utilizing the copy() operate

package deal primary

import "fmt"

func primary() {
    src := []string{"a", "b", "c"}
    dst := make([]string, len(src))

    copy(dst, src)

    fmt.Printf("supply slice: %[1]v, handle: %[1]pn", src)
    fmt.Printf("supply slice: %[1]v, handle: %[1]pn", dst)
}

Output:

supply slice: [a b c], handle: 0xc000098180
supply slice: [a b c], handle: 0xc0000981b0

As you may see, we bought two totally different addresses of underlying arrays for the src and dst slices, which is proof that we deeply cloned the src slice. The copy() operate copies min(len(dst), len(src)) components, so we have to create the dst slice of the identical dimension because the src utilizing make([]string, len(src)).

Copy a slice utilizing the append() operate

package deal primary

import "fmt"

func primary() {
    src := []string{"a", "b", "c"}
    var dst []string

    dst = append(dst, src...)

    fmt.Printf("supply slice: %[1]v, handle: %[1]pn", src)
    fmt.Printf("supply slice: %[1]v, handle: %[1]pn", dst)
}

Output:

supply slice: [a b c], handle: 0xc000098180
supply slice: [a b c], handle: 0xc0000981b0

Copying a slice utilizing the append() operate is actually easy. You simply must outline a brand new empty slice, and use the append() so as to add all components of the src to the dst slice. In that method, you get a brand new slice with all the weather duplicated.

Shallow copy by task

package deal primary

import "fmt"

func primary() {
    src := []string{"a", "b", "c"}
    dst := src

    fmt.Printf("supply slice: %[1]v, handle: %[1]pn", src)
    fmt.Printf("supply slice: %[1]v, handle: %[1]pn", dst)
}

Output:

supply slice: [a b c], handle: 0xc000098180
supply slice: [a b c], handle: 0xc000098180

If you happen to simply assign the src slice to the brand new dst variable, you get a shallow copy that has the identical underlying array. If you modify the contents of this copy, the unique slice may also change.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments