Skip to content

Instantly share code, notes, and snippets.

@mohae
Created October 4, 2016 17:35
Show Gist options
  • Select an option

  • Save mohae/ab31ae7d2c98c2cbf91f20f7266bb29b to your computer and use it in GitHub Desktop.

Select an option

Save mohae/ab31ae7d2c98c2cbf91f20f7266bb29b to your computer and use it in GitHub Desktop.
deepcopy example
package main
import (
"encoding/json"
"fmt"
"time"
"github.com/mohae/deepcopy"
)
type Foo struct {
Location string
Reservation time.Time
Items []string
}
func main() {
foo := Foo{
Location: "Milliways",
Reservation: time.Now(),
Items: []string{"pangalactic gargleblaster", "steak"},
}
// make a copy: we get an interface{} back
c := deepcopy.Copy(foo)
// assert the interface to its underlying type
bar, ok := c.(Foo)
if !ok {
fmt.Println("error: unable to assert copy of foo as Foo")
return
}
// Print the original and copy
formattedOutput("original", foo)
formattedOutput("copy", bar)
// Modify the copy
bar.Location = "Art's Cafe"
bar.Items[0] = "Bibimbap"
bar.Items[1] = "bulgolgi"
//Print the original and copy; only the copy has changed.
formattedOutput("original", foo)
formattedOutput("copy", bar)
}
func formattedOutput(name string, v Foo) {
b, err := json.MarshalIndent(v, "", "\t")
if err != nil {
panic(err)
}
fmt.Printf("%s:\n%s\n\n", name, string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment