Last active
February 8, 2022 15:27
-
-
Save uloureiro/e11edae5ba63f89915c4a1d3eff50200 to your computer and use it in GitHub Desktop.
Mutation pattern in Go
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" | |
) | |
// This mutation pattern allows mutating an object without having to instantiate | |
// it first. This is specially useful in tests where you need to do small changes | |
// in the object's state based on a default initializtion value. | |
func main() { | |
fmt.Println(NewDefaultBicycle()) | |
fmt.Println(NewDefaultBicycle(func(b *Bicycle) { | |
b.FrameSize = "54" | |
})) | |
} | |
type Bicycle struct { | |
WheelSize string | |
FrameSize string | |
RearCogs []int | |
FrontCogs []int | |
} | |
// NewDefaultBicycle creates a new Bicycle with default values but allows mutation | |
// via the func argument. | |
func NewDefaultBicycle(mutate ...func(*Bicycle)) Bicycle { | |
b := Bicycle{ | |
WheelSize: "700c", | |
FrameSize: "M", | |
RearCogs: []int{11, 12, 13, 14, 15, 17, 19, 21, 23, 25, 28}, | |
FrontCogs: []int{42, 55}, | |
} | |
if mutate != nil { | |
for _, m := range mutate { | |
m(&b) | |
} | |
} | |
return b | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment