如何初始化Go结构体中的成员
我是 Golang 新手,所以其中的分配让我发疯:
import "sync"
type SyncMap struct {
lock *sync.RWMutex
hm map[string]string
}
func (m *SyncMap) Put (k, v string) {
m.lock.Lock()
defer m.lock.Unlock()
m.hm[k] = v, true
}
后来,我只是调用:
sm := new(SyncMap)
sm.Put("Test, "Test")
此时我遇到了 nil 指针恐慌。
我已经通过使用另一个函数并在 new() 之后调用它来解决这个问题:
func (m *SyncMap) Init() {
m.hm = make(map[string]string)
m.lock = new(sync.RWMutex)
}
但我想知道是否可以摆脱这个样板初始化?
I am new to Golang so allocation in it makes me insane:
import "sync"
type SyncMap struct {
lock *sync.RWMutex
hm map[string]string
}
func (m *SyncMap) Put (k, v string) {
m.lock.Lock()
defer m.lock.Unlock()
m.hm[k] = v, true
}
and later, I just call:
sm := new(SyncMap)
sm.Put("Test, "Test")
At this moment I get a nil pointer panic.
I've worked around it by using another one function, and calling it right after new()
:
func (m *SyncMap) Init() {
m.hm = make(map[string]string)
m.lock = new(sync.RWMutex)
}
But I wonder, if it's possible to get rid of this boilerplate initializing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你只需要一个构造函数。一个常见的使用模式是,
如果结构中有更多字段,启动一个 goroutine 作为后端,或者注册一个终结器,一切都可以在此构造函数中完成。
You just need a constructor. A common used pattern is
In case of more fields inside your struct, starting a goroutine as backend, or registering a finalizer everything could be done in this constructor.
由于互斥体未初始化,“Mue”的解决方案不起作用。以下修改有效:
http://play.golang.org/p/n-jQKWtEy5
The solution of 'Mue' doesn't work since the mutex is not initialized. The following modification works:
http://play.golang.org/p/n-jQKWtEy5
执事抓得好。 Mue 可能正在考虑更常见的模式,将锁作为值而不是指针包含在内。由于互斥体的零值是一种随时可用的未锁定互斥体,因此它不需要初始化,并且包含 1 作为值是很常见的。为了进一步简化,您可以通过省略字段名称来嵌入它。然后,您的结构体获取互斥体的方法集。请参阅此工作示例,http://play.golang.org/p/faO9six-Qx。我还去掉了 defer 的使用。在某种程度上,这是一个偏好和编码风格的问题,但由于它确实有很小的开销,所以我倾向于不在小函数中使用它,特别是在没有条件代码的情况下。
Good catch by deamon. Mue was possibly thinking of the more common pattern of including the lock as a value rather than a pointer. Since the zero value of a Mutex is a ready-to-use unlocked Mutex, it requires no initialization and including one as a value is common. As a further simplification, you can embed it by omitting the field name. Your struct then acquires the method set of the Mutex. See this working example, http://play.golang.org/p/faO9six-Qx. Also I took out the use of defer. To some extent it's a matter of preference and coding style, but since it does have a small overhead, I tend not to use it in small functions, especially if there is no conditional code.