极乌客

我的一些笔记和日记

Golang 可选参数实现

在部分方法例如公共方法中,为了平衡懒得填完参数和需要高度配置,又不想写那么多函数重载

可以使用这个方式

在这个方式下,可以在做这个方法参数的调整的同时不修改函数签名

还能实现默认参数

例子:

// ServerOption 是一个用于配置 Server 的选项。
type ServerOption struct {
	f func(*Server)
}

// Server 表示服务器配置。
type Server struct {
	Address string
	Port    int
}

// NewServer 创建一个新的 Server,并应用所有给定的配置选项。
func NewServer(options ...ServerOption) *Server {
	s := &Server{
		Address: "localhost",
		Port:    8080,
	}
	for _, option := range options {
		option.f(s)
	}
	return s
}

// WithAddress 返回一个配置 Server 地址的选项。
func WithAddress(address string) ServerOption {
	return ServerOption{func(s *Server) {
		s.Address = address
	}}
}

// WithPort 返回一个配置 Server 端口的选项。
func WithPort(port int) ServerOption {
	return ServerOption{func(s *Server) {
		s.Port = port
	}}
}

func main() {
	// 创建一个 Server,使用默认配置。
	server1 := NewServer()
	fmt.Printf("Server1: Address=%s, Port=%d\n", server1.Address, server1.Port)

	// 创建一个 Server,配置自定义地址。
	server2 := NewServer(WithAddress("192.168.1.1"))
	fmt.Printf("Server2: Address=%s, Port=%d\n", server2.Address, server2.Port)

	// 创建一个 Server,配置自定义端口。
	server3 := NewServer(WithPort(9090))
	fmt.Printf("Server3: Address=%s, Port=%d\n", server3.Address, server3.Port)

	// 创建一个 Server,配置自定义地址和端口。
	server4 := NewServer(WithAddress("10.0.0.1"), WithPort(8081))
	fmt.Printf("Server4: Address=%s, Port=%d\n", server4.Address, server4.Port)
}

Donut 与原生的两次相遇

上一篇
评论
发表评论 说点什么
还没有评论