Puppollo
3/14/2018 - 12:26 PM

options

set private fields through options

package main

import "fmt"

type (
	Option func(s *Some) error

	Some struct {
		intVal    int
		stringVal string
		boolVal   bool
	}
)

func NewSome(opt ...Option) Some {
	s := Some{}
	for _, o := range opt {
		err := o(&s)
		if err != nil {
			panic(err)
		}
	}
	return s
}

func SetInt(i int) Option {
	return func(s *Some) error {
		s.intVal = i
		return nil
	}
}

func SetBool(b bool) Option {
	return func(s *Some) error {
		s.boolVal = b
		return nil
	}
}

func SetString(str string) Option {
	return func(s *Some) error {
		s.stringVal = str
		return nil
	}
}

func main() {
	s := NewSome(SetString("test"), SetBool(true))

	fmt.Printf("%+v\n", s)

}