如何在Go结构中初始化成员 [英] How to initialize members in Go struct

查看:111
本文介绍了如何在Go结构中初始化成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Golang的新手,因此它的配置让我疯狂:
$ b

  importsync

type SyncMap struct {
lock * sync.RWMutex
hm map [string] string
}
func(m * SyncMap)Put(k,v string){
m.lock.Lock()
推迟m.lock.Unlock()

m.hm [k] = v,true
}
code>

以后,我只是打电话:

  sm:= new(SyncMap)
sm.Put(Test,Test)

在这一刻,我得到一个零指针恐慌。



我使用另外一个函数来处理它,并在<$ c之后调用它
$ b

  func(m * SyncMap)Init(){
m.hm = make(map [string] string)
m.lock = new(sync.RWMutex)
}

但我想知道,是否有可能摆脱这种样板初始化?

解决方案

<你只是需要一个构造函数。常用的模式是:

$ p $ func NewSyncMap()* SyncMap {
return& SyncMap {hm:make(map [string] string)}
}

一个goroutine作为后端,或者注册一个终结器,一切都可以在这个构造器中完成。

  func NewSyncMap()* SyncMap {
sm:= SyncMap {
hm:make(map [string] string),
foo:Bar,
}

runtime.SetFinalizer(sm ,(* SyncMap).stop)

go sm.backend()

return& sm
}


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?

解决方案

You just need a constructor. A common used pattern is

func NewSyncMap() *SyncMap {
    return &SyncMap{hm: make(map[string]string)}
}

In case of more fields inside your struct, starting a goroutine as backend, or registering a finalizer everything could be done in this constructor.

func NewSyncMap() *SyncMap {
    sm := SyncMap{
        hm: make(map[string]string),
        foo: "Bar",
    }

    runtime.SetFinalizer(sm, (*SyncMap).stop)

    go sm.backend()

    return &sm
}

这篇关于如何在Go结构中初始化成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆