Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import "fmt"
- const defaultA = 100
- const defaultB = 200
- const defaultC = 300
- type thing struct {
- // Mandatory parameters
- x int
- y int
- z int
- // Optional parameters with defaults
- a int
- b int
- c int
- }
- type thingOpt func(*thing)
- func newThing(x, y, z int, opts ...thingOpt) *thing {
- new := &thing{
- x: x,
- y: y,
- z: z,
- a: defaultA,
- b: defaultB,
- c: defaultC,
- }
- for _, o := range opts {
- o(new)
- }
- return new
- }
- func withA(a int) func(*thing) {
- return func(t *thing) {
- t.a = a
- }
- }
- func withB(b int) func(*thing) {
- return func(t *thing) {
- t.b = b
- }
- }
- func withC(c int) func(*thing) {
- return func(t *thing) {
- t.c = c
- }
- }
- func main() {
- t := newThing(1, 2, 3, withA(10), withB(20))
- fmt.Println("Thing: ", *t)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement