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.

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog