英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论