Skip to content

Instantly share code, notes, and snippets.

@sylr
Created May 27, 2019 11:57
Show Gist options
  • Select an option

  • Save sylr/46cb1df47edbe4b7065d094e7678b9be to your computer and use it in GitHub Desktop.

Select an option

Save sylr/46cb1df47edbe4b7065d094e7678b9be to your computer and use it in GitHub Desktop.
Clone object in golang
package main
import (
"fmt"
)
type Wheel struct {
// Diameter Wheel diameter in centimeters
Diameter int64
}
func (w Wheel) Clone() *Wheel {
return &Wheel{
Diameter: w.Diameter,
}
}
type Car struct {
Registration string
FrontRightWheel *Wheel
FrontLeftWheel *Wheel
RearRightWheel *Wheel
RearLeftWheel *Wheel
}
func (c Car) Clone() Car {
return Car{
Registration: c.Registration,
FrontRightWheel: c.FrontRightWheel.Clone(),
FrontLeftWheel: c.FrontLeftWheel.Clone(),
RearRightWheel: c.RearRightWheel.Clone(),
RearLeftWheel: c.RearLeftWheel.Clone(),
}
}
func main() {
wheel1 := &Wheel{Diameter: 80}
wheel2 := &Wheel{Diameter: 77}
car1 := &Car{
Registration: "CAR-1",
FrontRightWheel: wheel1,
FrontLeftWheel: wheel1,
RearRightWheel: wheel1,
RearLeftWheel: wheel1,
}
car2 := (car1)
car2.Registration = "CAR-2"
car3 := (car1)
car3.Registration = "CAR-3"
fmt.Printf("%#v\n", car1)
fmt.Printf("%#v\n", car2)
fmt.Printf("%#v\n", car3)
fmt.Println("-------------")
car1.RearLeftWheel = wheel2
fmt.Printf("%#v\n", car1)
fmt.Printf("%#v\n", car2)
fmt.Printf("%#v\n", car3)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment