Skip to content

Instantly share code, notes, and snippets.

@maxclav
Last active December 19, 2022 03:45
Show Gist options
  • Save maxclav/b669496c49eea3c404c6dd529699e65d to your computer and use it in GitHub Desktop.
Save maxclav/b669496c49eea3c404c6dd529699e65d to your computer and use it in GitHub Desktop.
Prototype Design Pattern example in Go (GoLang).
package main
import "fmt"
/*
In go, primitive types, and structs containing only primitive types, are copied by value.
You can copy them by simply assigning to a new variable (or returning from a function).
If your struct happens to include arrays, slices, or pointers, then you'll need to perform a deep copy of the referenced objects
unless you want to retain references between copies.
Source: https://stackoverflow.com/questions/51635766/how-do-i-copy-a-struct
This means you don't need the prototype patterns in most cases.
If you need it, just make a method to deepcopy the "prototype".
You can do it yourself or use any pkg like https://github.com/jinzhu/copier
*/
type Person struct {
Name string
Age int
Mother, Father *Person
}
func (p *Person) String() string {
str := fmt.Sprintf("%s (%v)", p.Name, p.Age)
if p.Mother != nil || p.Father != nil {
str += " son of "
if p.Mother != nil {
str += p.Mother.Name
}
if p.Mother != nil && p.Father != nil {
str += " and "
}
if p.Father != nil {
str += p.Father.Name
}
}
return str
}
func main() {
mom := Person{"Mariette", 51, nil, nil}
dad := Person{"Andre", 55, nil, nil}
max := Person{"Maxime", 30, &mom, &dad}
fmt.Printf("max: %s\n\n", &max)
brother := max
brother.Name = "Robert"
fmt.Printf("bob (copied from max and changing name): %s\n", &brother)
fmt.Printf("max (after changing the name of bob): %s\n\n", &max)
brother.Mother.Name = "Antoinette"
fmt.Printf("bob (after changing name of her mother): %s\n", &brother)
fmt.Printf("max (after changing the name of the mother of bob): %s\n\n", &max)
brother.Mother = &Person{"Denise", 57, nil, nil}
fmt.Printf("bob (after changing mother pointer): %s\n", &brother)
fmt.Printf("max (after changing mother pointer of bob): %s\n", &max)
}
@maxclav
Copy link
Author

maxclav commented Dec 19, 2022

This will print:

max: Maxime (30) son of Mariette and Andre

bob (copied from max and changing name): Robert (30) son of Mariette and Andre
max (after changing the name of bob): Maxime (30) son of Mariette and Andre

bob (after changing name of her mother): Robert (30) son of Antoinette and Andre
max (after changing the name of the mother of bob): Maxime (30) son of Antoinette and Andre

bob (after changing mother pointer): Robert (30) son of Denise and Andre
max (after changing mother pointer of bob): Maxime (30) son of Antoinette and Andre

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment