英文:
Best practices, How to initialize custom types?
问题
我还不习惯使用go的方式来做事情。
这里我有一个包装了BidiMap的类型ClientConnectorPool。我应该如何初始化这个类型?这样我就可以在之后添加到我的bidiMap中了。我尝试过的所有方法都很笨拙,我需要一些灵感,我能为它实现一些类似make(ClientConnectorPool)的函数吗?
在我的脑海中,它应该是这样的,但是我所有的解决方案都是为了避免空指针错误而写的15行代码
CC = make(ClientConnectorPool)
CC.Add("foo","bar")
代码:
package main
import ()
type ClientConnectorPool struct {
Name string
ConnectorList BidirMap
}
func (c ClientConnectorPool) Add(key, val interface{}){
c.ConnectorList.Add(key,val)
}
type BidirMap struct {
left, right map[interface{}]interface{}
}
func (m BidirMap) Add(key, val interface{}) {
if _, inleft := m.left[key]; inleft {
delete(m.left, key)
}
if _, inright := m.right[val]; inright {
delete(m.right, val)
}
m.left[key] = val
m.right[val] = key
}
英文:
I'm still not used to the go way of doing things.
Here I have the type ClientConnectorPool that wraps a BidiMap. How should I initialize this type? So that I can add to my bidiMap afterwords? All my attempt's of doing this sames hackish and I need inspiration, can I implement some sort om make(ClientConnectorPool) function for it?
In my head it should look like this but all my solutions is like 15 lines of code to avoid nil pointer errors
CC = make(ClientConnectorPool)
CC.Add("foo","bar")
Code:
package main
import ()
type ClientConnectorPool struct {
Name string
ConnectorList BidirMap
}
func (c ClientConnectorPool) Add(key, val interface{}){
c.ConnectorList.Add(key,val)
}
type BidirMap struct {
left, right map[interface{}]interface{}
}
func (m BidirMap) Add(key, val interface{}) {
if _, inleft := m.left[key]; inleft {
delete(m.left, key)
}
if _, inright := m.right[val]; inright {
delete(m.right, val)
}
m.left[key] = val
m.right[val] = key
}
答案1
得分: 3
你不能为make()定义自定义函数。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{}),
},
}
}
你也可以有一个NewBidirMap
函数来封装该结构的创建。
我不明白你为什么需要检查nil。make()
不会返回nil,其余部分只是一个简单的结构体字面量。
英文:
You cannot define custom functions for make(). Make only works on slices, maps and channels (and custom types that have those representations).
Idiomatic Go would be to have a NewClientConnectorPool
function (in the following abbreviated to NewPool
) that creates and returns it.
func NewPool(name string) ClientConnectorPool {
return ClientConnectorPool{
Name: name,
ConnectorList: BidirMap{
left: make(map[interface{}]interface{}),
right: make(map[interface{}]interface{}),
},
}
}
You could also have a NewBidirMap
function that wraps the creation of that struct.
I don't see where you need checks for nil though. make()
won't return nil, and the rest is a simple struct literal.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论