Skip to content

Instantly share code, notes, and snippets.

@aquilax
Last active December 31, 2021 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aquilax/437ee61fb23a320df412fe1e9ab38f03 to your computer and use it in GitHub Desktop.
Save aquilax/437ee61fb23a320df412fe1e9ab38f03 to your computer and use it in GitHub Desktop.
Go builder pattern
// https://go.dev/play/p/JSWYXbjHBlM
package main
import "fmt"
type Fruit struct {
name string
color string
shape string
}
func NewFruit() Fruit {
return Fruit{}
}
func NewFruitFromFruit(f Fruit) Fruit {
nf := f // works only for simple types
return nf
}
func (f Fruit) SetName(name string) Fruit {
f.name = name
return f
}
func (f Fruit) SetColor(color string) Fruit {
f.color = color
return f
}
func (f Fruit) SetShape(shape string) Fruit {
f.shape = shape
return f
}
func (f Fruit) Build() (Fruit, error) {
if f.name == "" {
return f, fmt.Errorf("name is required")
}
return f, nil
}
func main() {
apple, _ := NewFruit().SetName("apple").SetColor("red").SetShape("round").Build()
watermelon, _ := NewFruit().SetName("watermelon").SetColor("green").SetShape("round").Build()
greenApple, _ := NewFruitFromFruit(apple).SetColor("green").Build()
fmt.Printf("%+v\n", apple)
fmt.Printf("%+v\n", watermelon)
fmt.Printf("%+v\n", greenApple)
if _, err := NewFruit().Build(); err != nil {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment