1. 程式人生 > 實用技巧 >golang的rpc選項模式一點理解

golang的rpc選項模式一點理解

在學習rpc小冊子時遇到了server端傳參用了選項模式
如下是程式碼,註釋是自己對這塊的理解,希望對你能有些許幫助:

//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語言裡函式是單獨的自定義型別;方法是依附於某個自定義型別的函式