Skip to content

Instantly share code, notes, and snippets.

@xigang
Last active November 17, 2020 07:00
Show Gist options
  • Save xigang/29cb33ad37730000ebd31a43b6f86528 to your computer and use it in GitHub Desktop.
Save xigang/29cb33ad37730000ebd31a43b6f86528 to your computer and use it in GitHub Desktop.
Functional options for friendly APIs
//http://lubia.cn/2016/05/22/functional-options-for-friendly-apis/
//http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis
package main
import (
"fmt"
)
type Options struct {
Name string
Age int32
Addesss string
IdCard string
Cellphone string
}
type Option func(*Options)
func NewOptions(opts ...Option) (opt Options) {
for _, o := range opts {
o(&opt)
}
return
}
func Name(name string) Option {
return func(o *Options) {
o.Name = name
}
}
func Age(age int32) Option {
return func(o *Options) {
o.Age = age
}
}
func Address(addr string) Option {
return func(o *Options) {
o.Addesss = addr
}
}
func main() {
var opt Options
opt = NewOptions(
Name("xigang"),
Age(24),
Address("Beijing"))
fmt.Printf("%v", opt)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment