package main
import (
"fmt"
)
type options struct {
a int64
b string
c map[int]string
}
func NewOption(opt ...ServerOption) *options {
r := new(options)
for _, o := range opt {
o(r)
}
return r
}
type ServerOption func(*options)
func WriteA(s int64) ServerOption {
return func(o *options) {
o.a = s
}
}
func WriteB(s string) ServerOption {
return func(o *options) {
o.b = s
}
}
func WriteC(s map[int]string) ServerOption {
return func(o *options) {
o.c = s
}
}
func main() {
opt1 := WriteA(int64(1))
opt2 := WriteB("test")
opt3 := WriteC(make(map[int]string,0))
op := NewOption(opt1, opt2, opt3)
fmt.Println(op.a, op.b, op.c)
}
如上,最近看grpc的源碼,發(fā)現(xiàn)了里面一種高逼格的構(gòu)造函數(shù)的寫法涌哲,表示震驚胖缤,學(xué)到了新姿勢。
package main
import (
"fmt"
)
type options struct {
a int64
b string
c map[int]string
}
func (o *options) writeA(a int64) *options {
o.a = a
return o
}
func (o *options) writeB(b string) *options {
o.b = b
return o
}
func (o *options) writeC(c map[int]string) *options {
o.c = c
return o
}
func main() {
op := new(options)
op.writeA(int64(1)).writeB("test").writeC(make(map[int]string, 0))
fmt.Println(op.a, op.b, op.c)
}