Go 代码与项目组织的最佳实践与常见错误
1. 函数式选项模式
当客户端需要传递多个选项,并且要精确处理端口无效等情况时,错误处理会变得复杂。函数式选项模式依赖可变参数,能有效解决这一问题。
其主要思路如下:
- 一个未导出的结构体保存配置选项。
- 每个选项是一个返回相同类型的函数: type Option func(options *options) error 。
以下是 Go 语言实现选项结构体、 Option 类型和 WithPort 选项的代码:
type options struct {
port *int
}
type Option func(options *options) error
func WithPort(port int) Option {
return func(options *options) error {
if port < 0 {
return errors.New("port should be positive")
}
options.port = &port
return nil
}
}
NewServer 函数的实现如下:
func NewServer(addr string, opts
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



