donglipi4495 2017-05-08 22:42
浏览 32

如何防止在Go中初始化导出类型?

Edit: I'm not asking how to initialize variables correctly. I'm asking how to prevent them from being initialized incorrectly, so that functions that take that type don't have to explicitly validate their arguments.

In Go, I have a type that contains maps, e.g.:

package foo

type Bar struct {
  baz map[string]int
  total int
}

func NewBar() *Bar {
  return &Bar{baz: map[string]int{}}
}

func (b *Bar) IncrementBaz(key string) {
    f.baz[key] = f.baz[key] + 1
    f.total++
}

// ...

If another package initializes the type and then tries to write to it, it will try to write to a nil map, causing a segfault:

package main

import "foo"

func main() {
  var b foo.Bar
  b.IncrementBaz("some_key") // write to nil map -> segfault
  // ...
}

To prevent this, I want to make it so that other packages can't initialize an empty foo.Bar.

I can't simply make it unexported, because I want functions in other packages to be able to declare it as an argument or return type. If I wrap it in an interface, I get a similar problem:

package "foo"

type Bar interface {
  IncrementBaz(string)
  // ...
}

type bar struct {
  baz map[string]int
  total int
}

func NewBar() Bar {
  return &bar{baz: map[string]int{}}
}

func (b *bar) IncrementBaz(key string) {
    f.baz[key] = f.baz[key] + 1
    f.total++
}

// ...

Similar problem:

package main

import "foo"

func main() {
  var b foo.Bar
  b.IncrementBaz("some_key") // method call on nil interface -> segfault
  // ...
}

Is there any way to have an exported type that only the package that declares it can initialize it?

  • 写回答

1条回答 默认 最新

  • douli4337 2017-05-08 22:43
    关注

    Now foo.Bar is just an interface type. The default value is a nil pointer. You are very close, just initialize it as b := foo.NewBar()

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥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,如何解決?