去,初始化自定义类型

时间:2012-04-01 11:49:09

标签: initialization go

假设,我正在编写一个扫雷游戏,我有一个结构来保存游戏区域,其中包含一个带有地雷的2D阵列。假设,我想用一些地雷初始化它。有没有办法说gameField GameField = new(GameField, 30),类似于我在java中做的事情?

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

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

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

我想要的是调用初始化程序并自动执行scatterMines func。

2 个答案:

答案 0 :(得分:9)

我在Go结构中看到的模式是相应的NewXxx方法(例如,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)
    //...
}

答案 1 :(得分:2)

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

var GameField g
g.scatterMines(30)

另见http://golang.org/ref/spec#The_zero_value