去,初始化自定义类型

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

Go, init custom type

问题

假设我正在编写一个扫雷游戏,并且我有一个结构体来保存游戏场地,其中包含一个带有地雷的二维数组。假设我想用一些地雷来初始化它。是否有一种类似于Java中的<code>gameField GameField = new(GameField, 30)</code>的方式?

以下是一些代码来说明我的观点:

<code><pre>
type GameField struct {
field [20][20] int
}

func (this *GameField) scatterMines(numberOfMines int) {
//一些逻辑来随机放置numberOfMines个地雷
}
</pre></code>

我想要的是调用一个初始化函数,并自动执行<code>scatterMines</code>函数。

英文:

Suppose, I am writing a minesweeper game, and i have a struct to hold the game field, that contains a 2D array with mines. Suppose, i want to initialize it with some mines. Is there a way to say <code>gameField GameField = new(GameField, 30)</code>, similar to what i'd do in java?

Here is some code to illustrate my point:

<code><pre>
type GameField struct {
field [20][20] int
}

func (this *GameField) scatterMines(numberOfMines int) {
//some logic to place the numberOfMines mines randomly
}
</pre></code>

What i want is to call an initializer and have that <code>scatterMines</code> func executed automatically.

答案1

得分: 9

我在Go结构体中看到的一种模式是相应的NewXxx方法(例如,image pkg):

type GameField struct {
  field [20][20] int
}

func NewGameField(numberOfMines int) *GameField {
  g := new(GameField)
  //一些逻辑来随机放置numberOfMines个地雷
  //...
  return g
}

func main() {
	g := NewGameField(30)
    //...
}
英文:

A pattern I've seen in Go structs is a corresponding NewXxx method (e.g., image pkg):

type GameField struct {
  field [20][20] int
}

func NewGameField(numberOfMines int) *GameField {
  g := new(GameField)
  //some logic to place the numberOfMines mines randomly
  //...
  return g
}

func main() {
	g := NewGameField(30)
    //...
}

答案2

得分: 2

Go对象没有构造函数,因此无法在变量初始化时自动执行scatterMines函数。您需要显式调用该方法:

var GameField g
g.scatterMines(30)

参见http://golang.org/ref/spec#The_zero_value。

英文:

Go objects have no constructors, so there is no way to have scatterMines function executed automatically at variable initialization. You need to call the method explicitly:

var GameField g
g.scatterMines(30)

See also http://golang.org/ref/spec#The_zero_value.

huangapple
  • 本文由 发表于 2012年4月1日 19:49:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/9964117.html
匿名

发表评论

匿名网友

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

确定