We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
type Server struct { Addr string Port int Timeout time.Duration MaxConns int }
import "time" func New(addr string, port int, timeout *time.Duration, maxConns *int) *Server { s := &Server{ Addr: addr, Port: port, Timeout: 10 * time.Second, MaxConns: 100, } if timeout != nil { s.Timeout = *timeout } if maxConns != nil { s.MaxConns = *maxConns } return s } func NewWithTimeout(addr string, port int, timeout time.Duration) *Server { s := &Server{ Addr: addr, Port: port, Timeout: timeout, MaxConns: 100, } return s } func NewWithMaxConns(addr string, port int, maxConns int) *Server { s := &Server{ Addr: addr, Port: port, Timeout: 10 * time.Second, MaxConns: maxConns, } return s } func NewWithTimeoutMaxConns(addr string, port int, timeout time.Duration, maxConns int) *Server { s := &Server{ Addr: addr, Port: port, Timeout: timeout, MaxConns: maxConns, } return s }
客户端初始化代码:
server := NewWithTimeout("127.0.0.1", 8000, 5*time.Second)
import "time" type ServerBuilder struct { Server } func (sb *ServerBuilder) Create(addr string, port int) *ServerBuilder { return &ServerBuilder{ Server: Server{ Addr: addr, Port: port, Timeout: 10 * time.Second, MaxConns: 100, }, } } func (sb *ServerBuilder) WithTimeout(timeout time.Duration) *ServerBuilder { sb.Server.Timeout = timeout return sb } func (sb *ServerBuilder) WithMaxConns(maxConns int) *ServerBuilder { sb.Server.MaxConns = maxConns return sb } func (sb *ServerBuilder) Build() *Server { return &sb.Server }
sb := ServerBuilder{} server := sb.Create("127.0.0.1", 8000).WithTimeout(5 * time.Second).Build()
type Option func(*Server) func TimeOut(timeout time.Duration) Option { return func(s *Server) { s.Timeout = timeout } } func MaxConns(maxCon int) Option { return func(s *Server) { s.MaxConns = maxCon } } func New(addr string, port int, options ...Option) *Server { server := &Server{ Addr: addr, Port: port, Timeout: 10 * time.Second, MaxConns: 100, } for _, opt := range options { opt(server) } return server }
server := New("127.0.0.1", 8000, TimeOut(5*time.Second))
The text was updated successfully, but these errors were encountered:
No branches or pull requests
被初始化的 struct
使用多个初始化函数
客户端初始化代码:
使用 Builder 模式
客户端初始化代码:
functional options
客户端初始化代码:
The text was updated successfully, but these errors were encountered: