2012-04-01 89 views
1

假設我正在寫一個掃雷遊戲,並且我有一個結構來保存遊戲領域,其中包含一個包含地雷的二維數組。假設,我想用一些地雷初始化它。有沒有辦法說gameField GameField = new(GameField, 30),類似於我在java中做什麼?Go,init自定義類型

下面是一些代碼來說明我的觀點:

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

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

我要的是調用一個初始化,並有scatterMines FUNC自動執行。

回答

9

我在圍棋結構可見模式是對應的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) 
    //... 
} 
+3

當包只包含一個導出的類型時,我也看到了這種模式,只有新的形式。所以如果該軟件包被稱爲「gamefield」,那麼你可以只有一個新功能,並做gamefield.New() – jdi 2012-04-01 14:57:21

2

Go對象沒有構造函數,所以在變量初始化時無法自動執行scatterMines函數。您需要明確地調用該方法:

var GameField g 
g.scatterMines(30) 

另請參閱http://golang.org/ref/spec#The_zero_value

+0

這將是更準確的說,圍棋對象沒有*默認*構造函數。您可以製作自己的構造函數,但必須自己調用它們。 – 2012-04-03 02:56:59