Go 最佳实践,如何初始化自定义类型?
我还不习惯做事的方式。 这里我有一个ClientConnectorPool类型,它包装了一个BidiMap。我应该如何初始化此类型?这样我就可以添加到我的bidiMap后记中?我做这件事的所有尝试都是黑客行为,我需要灵感,我能为它实现某种om make(ClientConnectorPool)功能吗 在我看来,它应该是这样的,但我所有的解决方案都像15行代码,以避免零指针错误:DGo 最佳实践,如何初始化自定义类型?,go,Go,我还不习惯做事的方式。 这里我有一个ClientConnectorPool类型,它包装了一个BidiMap。我应该如何初始化此类型?这样我就可以添加到我的bidiMap后记中?我做这件事的所有尝试都是黑客行为,我需要灵感,我能为它实现某种om make(ClientConnectorPool)功能吗 在我看来,它应该是这样的,但我所有的解决方案都像15行代码,以避免零指针错误:D CC = make(ClientConnectorPool) CC.Add("foo","bar") 代码: 不能
CC = make(ClientConnectorPool)
CC.Add("foo","bar")
代码:
不能为make()定义自定义函数。“生成”仅适用于切片、贴图和通道(以及具有这些表示形式的自定义类型) 惯用的Go是使用一个
NewClientConnectorPool
函数(以下简称为NewPool
)创建并返回它
func NewPool(name string) ClientConnectorPool {
return ClientConnectorPool{
Name: name,
ConnectorList: BidirMap{
left: make(map[interface{}]interface{}),
right: make(map[interface{}]interface{}),
},
}
}
您还可以使用一个newbidermap
函数来包装该结构的创建
我看你哪里需要零的支票make()
不会返回nil,其余的是一个简单的结构文本
func NewPool(name string) ClientConnectorPool {
return ClientConnectorPool{
Name: name,
ConnectorList: BidirMap{
left: make(map[interface{}]interface{}),
right: make(map[interface{}]interface{}),
},
}
}