go - 在方法或构造函数级别进行零处理?
问题描述
我应该在构造函数中检查 nil 值,然后设置一个未导出的结构字段,还是通过在方法级别检查 nil 来使默认结构值有用?
type Foo struct{}
func (f *Foo) Baz() {}
var DefaultFoo = new(Foo)
type Bar struct {
Foo *Foo
}
func (b *Bar) Baz() {
if b.Foo == nil {
DefaultFoo.Baz()
} else {
b.Foo.Baz()
}
}
或者
type Foo struct{}
func (f *Foo) Baz() {}
var DefaultFoo = new(Foo)
type Bar struct {
foo *Foo
}
func NewBar(foo *Foo) *Bar {
if foo == nil {
foo = DefaultFoo
}
return &Bar{foo}
}
func (b *Bar) Baz() {
b.foo.Baz()
}
解决方案
我认为对此没有“正确”的答案。
话虽如此,在 Go 基础库中通常看到的方法是让对象在没有任何构造函数的情况下创建,在其字段中使用nil
orzero
值,然后使方法具有使用逻辑或返回有用的默认值。
以http.Client
实现为例:
https://github.com/golang/go/blob/master/src/net/http/client.go
它基本上让您只需执行以下操作即可创建一个新客户端:
client := &http.Client{}
如果要覆盖默认值,则可以填充对象的字段,否则它将检查nil
不同的方法以提供默认行为,例如:
https://github.com/golang/go/blob/master/src/net/http/client.go#L195
func (c *Client) transport() RoundTripper {
if c.Transport != nil {
return c.Transport
}
return DefaultTransport
}
推荐阅读
- reactjs - MomentJS - 如何更改语言环境但保留语言
- java - 在Java中的泛型类中实现特定类型的方法
- python - 打开文件浏览窗口后 Python 脚本停止执行
- c - NdisoidRequest 状态返回成功但未设置数据包过滤器
- pandas - read_csv 的箱形图失败
- node.js - 没有 Redis/DB 的 NodeJS 刷新令牌
- javascript - 使用 Flask 在单页应用程序中提交表单,无需重新加载
- selenium - 使用 selenium 时 Firefox 的浏览器启动参数是什么?
- google-app-engine - 将简单的 golang 应用程序部署到 appengine 已停止工作
- struct - 为什么 Rust 允许返回当前函数拥有的引用?