dpqjvoq9033 2014-03-29 20:32
浏览 39
已采纳

是否有针对“构造函数”的标准惯用Go?

Given the following:

type AStruct struct {
    m_Map map[int]bool
}

In this case, an instance ofAStructcannot be used untilAStruct.m_Mapis initialized:

m_Map=make(map[int]bool,100)

I have taken to writing an Init()function for my structs in such cases:

func (s *AStruct) Init() {
    s.m_Map=make(map[int]bool,100)
}

I don't particularly care for this design, because it requires(s *AStruct) Init() to be public and mandates that clients call it explicitly before using an instance of AStuct - in the interim an unusable instance ofAStuctis out there, waiting to generate apanic.

I could make init() private and declare an initialized boolflag in thestruct set ittrueininit()after everything is initialized and check in each method:

func (s *AStruct) DoStuff {

    if !s.initialized {
         s.init()
    }

    s.m_Map[1]=false
    s.m_Map[2]=true
}

But this is awkward and adds superfluous code.

Is there is standard way of handling this in Go? One that guarantees m_Map will be initialized without relying on clients to call Init()?

  • 写回答

1条回答 默认 最新

  • douyu2817 2014-03-29 21:17
    关注

    The standard for a type Foo is to write a constructor NewFoo() which is not a method on the type, but returns a value of type Foo (or *Foo). Then as long as all instances of Foo are generated through a call to NewFoo() (and not through a literal or a call to the new() builtin) then you're safe.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?