Last active
December 31, 2021 18:13
-
-
Save aquilax/437ee61fb23a320df412fe1e9ab38f03 to your computer and use it in GitHub Desktop.
Go builder pattern
This file contains hidden or 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
// 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