Golang multidimensional slice copy

Viewed 6148

I was trying to make a clone of multidimensional slice, because when I have changed elements in the duplicated slice, the elements in the original one were overwritten also.

The only method that worked for me was:

duplicate := make([][]int, len(matrix))
for i := 0; i < len(matrix); i++ {
    duplicate[i] = make([]int, len(matrix[0]))
    for j := 0; j < len(matrix[0]); j++ {
        duplicate[i][j] = matrix[i][j]
    }
}

is there any other way - shorter or more efficient to achieve the same result? thanks

2 Answers

You could roundtrip it through gob:

package main

import (
   "bytes"
   "encoding/gob"
   "fmt"
)

func sliceCopy(in, out interface{}) {
   buf := new(bytes.Buffer)
   gob.NewEncoder(buf).Encode(in)
   gob.NewDecoder(buf).Decode(out)
}

func main() {
   a := [][]int{
      {1, 2, 3}, {4, 5, 6}, {7, 8, 9},
   }
   var b [][]int
   sliceCopy(a, &b)
   fmt.Println(b)
}

https://golang.org/pkg/encoding/gob

Related