angry_gopher
angry_gopher

Reputation: 1725

Function for copying arrays in Go language

Is there any built-in function in Go for copying one array to another? Will this work in case of two (or more) dimensional arrays?

Upvotes: 32

Views: 74737

Answers (4)

morteza khadem
morteza khadem

Reputation: 514

If you don't care about the speed:

import "golang.org/x/exp/slices"

tmp := slices.Clone(arr)

With Go 1.18 and generics, any slices now could be copied with slices.Clone from package "golang.org/x/exp/slices".

Upvotes: 2

user187676
user187676

Reputation:

Use copy http://play.golang.org/p/t7P6IliMOK

a := []int{1, 2, 3}
var b [3]int

fmt.Println("A:", a)
fmt.Println("B:", b)

copy(b[:], a)

fmt.Println("A:", a)
fmt.Println("B2:", b)

b[1] = 9

fmt.Println("A:", a)
fmt.Println("B3:", b)

OUT:

A: [1 2 3]
B: [0 0 0]
A: [1 2 3]
B2: [1 2 3]
A: [1 2 3]
B3: [1 9 3]

Upvotes: 10

alecbz
alecbz

Reputation: 6498

Is there any built-in function in Go language for copying one array to another?

Yes: http://play.golang.org/p/_lYNw9SXN5

a := []string{
    "hello",
    "world",
}
b := []string{
    "goodbye",
    "world",
}

copy(a, b)

// a == []string{"goodbye", "world"}

Will this work in case of two (or more) dimensional arrays?

copy will do a shallow copy of the rows: http://play.golang.org/p/0gPk6P1VWh

a := make([][]string, 10)

b := make([][]string, 10)
for i := range b {
    b[i] = make([]string, 10)
    for j := range b[i] {
        b[i][j] = strconv.Itoa(i + j)
    }
}

copy(a, b)

// a and b look the same

b[1] = []string{"some", "new", "data"}

// b's second row is different; a still looks the same

b[0][0] = "apple"

// now a looks different

I don't think there's a built-in for doing deep-copys of multi-dimensional arrays: you can do it manually like: http://play.golang.org/p/nlVJq-ehzC

a := make([][]string, 10)

b := make([][]string, 10)
for i := range b {
    b[i] = make([]string, 10)
    for j := range b[i] {
        b[i][j] = strconv.Itoa(i + j)
    }
}

// manual deep copy
for i := range b {
    a[i] = make([]string, len(b[i]))
    copy(a[i], b[i])
}

b[0][0] = "apple"

// a still looks the same

edit: As pointed out in the comments, I assumed by "copy an array" you meant "do a deep copy of a slice", as arrays can be deep-copied with the = operator as per jnml's answer (because arrays are value types): http://play.golang.org/p/8EuFqXnqPB

Upvotes: 44

zzzz
zzzz

Reputation: 91439

The primary "function" for copying an array in Go is the assignment operator =, as it is the case for any other value of any other type.

package main

import "fmt"

func main() {
        var a, b [4]int
        a[2] = 42
        b = a
        fmt.Println(a, b)

        // 2D array
        var c, d [3][5]int
        c[1][2] = 314
        d = c
        fmt.Println(c)
        fmt.Println(d)
}

Playground


Output:

[0 0 42 0] [0 0 42 0]
[[0 0 0 0 0] [0 0 314 0 0] [0 0 0 0 0]]
[[0 0 0 0 0] [0 0 314 0 0] [0 0 0 0 0]]

Upvotes: 23

Related Questions