结构体类型是否有构造函数接口?

huangapple go评论88阅读模式
英文:

Is there a constructor interface for a struct type?

问题

在golang中,假设我有一个类型,在使用之前需要进行一些设置,而不仅仅是设置默认值。例如:

type dice struct {
    input   string
    count   int
    sides   int
    result  int
}

func (d *dice) Roll() {
    // 初始化随机种子
    rand.Seed(time.Now().UnixNano())
    for i := 0; i < d.count; i++ {
        d.result = d.result + rand.Intn(d.sides)+1)
    }
}

这只是一个简单的例子,但是如果我想在创建dice类型的实例时自动调用d.Roll(),有没有办法做到这一点?更符合我要解决的问题,假设我想在调用Roll()之前自动调用rand.Seed(time.Now().UnixNano()),有没有一种符合golang惯例的方法来实现这个?

基本上,我的问题是“如何在golang中处理构造函数功能?”是否有一个接口可以添加?

英文:

In golang, say I have a type that needs some setup done on it before use beyond just setting default values. ex:

type dice struct {
    input   string
    count   int
    sides   int
    result  int
}

func (d *dice) Roll() {
    //initialize random seed
    rand.Seed(time.Now().UnixNano())
    for i := 0; i &lt; d.count; i++ {
        d.result = d.result + rand.Intn(d.sides)+1)
    }
}

Simple example but say if I wanted to have d.Roll() called automatically when creating an instance of the 'dice' type is there a way to do that? More in line with the issue I'm trying to solve, say I wanted the rand.Seed(time.Now().UnixNano()) bits to be called automatically before I call Roll() is there an idiomatic golang way to do this?

Basically "How do you handle constructor functionality in golang?" is my question. Is there an interface for this I can add?

答案1

得分: 1

不,Go语言不提供这种类型的接口。你不能像在C++中那样使用构造函数。

目前的惯用方式是创建一个函数:

func NewX(args...) X // 或 *X

在这个函数中,你可以按照你的需求设置结构体。在你的情况下,可以像这样编写:

func NewDice() dice {
  var d dice
  d.Roll()
  return d
}
英文:

No, Go doesn't provide this kind of interface. You just can't use a constructor like you would do in C++ by example.

The current idiom is to create a function

NewX(args...) X // or *X

in which you can setup your struct as you want. In your case, it could look like this:

func NewDice() dice {
  var d dice
  d.Roll()
  return d
}

答案2

得分: 0

没有。但是常见的、我会说是惯用的做法是在你的包中放置一个 func NewDice() dice,然后你可以直接调用它来获取一个实例。在那里进行设置。它的作用与构造函数相同。在包级别上拥有像 NewMyType 这样的方法来进行初始化并返回一个实例是相当常见的。

英文:

There is not. But the common, and I would say idiomatic, thing to do is to put a func NewDice() dice in your package and then you can just call it to get an instance. Do your set up there. It serves the same purpose as a constructor. It's pretty common to have package level methods like NewMyType that do initilization and return and instance.

huangapple
  • 本文由 发表于 2015年9月25日 02:18:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/32768261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定