Last active
December 19, 2022 03:45
-
-
Save maxclav/b669496c49eea3c404c6dd529699e65d to your computer and use it in GitHub Desktop.
Prototype Design Pattern example in Go (GoLang).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will print: