在学习rpc小册子时遇到了server端传参用了选项模式
前提:要记住在go语言里函数也是一种变量类型,和自定义的其它类型一样,也可以作为值传递,也可以当作结果赋值
如下是代码,注释是自己对这块的理解,希望对你能有些许帮助:
//ServerOptions 结构体类型
type ServerOptions struct {
address string
network string
}
//ServerOption 函数类型,参数是ServerOptions这个结构体的值
type ServerOption func(*ServerOptions)
//WithAddress 函数的返回类型是ServerOption,因为return的匿名函数是上面ServerOption的函数值
func WithAddress(address string) ServerOption{
return func(o *ServerOptions) {
o.address = address
}
}
//WithNetwork 同上
func WithNetwork(network string) ServerOption {
return func(o *ServerOptions) {
o.network = network
}
}
type Server struct {
opts *ServerOptions
}
func NewServer(opt ...ServerOption) *Server{
s := &Server {
opts : &ServerOptions{},
}
for _, o := range opt {
o(s.opts)
}
}
//对o(s.opts)的理解:
//这里的o是ServerOption这个函数类型数组里的值,即With函数;s.opts是ServerOptions结构体的指针;
//即o = func(o *ServerOptions) { o.network=network},此时o(s.opts)就是调用这个匿名函数,s.opts就是调用这个函数传的参数
//调用,创建server
opts := []ServerOption{
WithAddress("127.0.0.1:8000"),
WithNetwork("tcp"),
}
s := NewServer(opts ...)
注意
- 这个里面比较绕的是ServerOption这个函数类型和ServerOptions这个结构体类型,要注意区分下;
- golang语言里函数是单独的自定义类型;方法是依附于某个自定义类型的函数