【发布时间】:2011-09-08 09:21:24
【问题描述】:
来自Go documentation on method declarations:
接收器类型必须是 T 或 *T 形式,其中 T 是类型名称。 T 被称为接收器基本类型或只是基本类型。 基类型不能是指针或接口类型,并且必须与方法在同一个包中声明。
谁能告诉我为什么会这样?是否有任何其他(静态类型)语言允许这样做?我真的很想在接口上定义方法,这样我就可以将给定接口类型的任何实例视为另一个实例。例如(从Wikipedia article on the Template Method Pattern 中窃取示例)如果以下内容有效:
type Game interface {
PlayOneGame(playersCount int)
}
type GameImplementation interface {
InitializeGame()
MakePlay(player int)
EndOfGame() bool
PrintWinner()
}
func (game *GameImplementation) PlayOneGame(playersCount int) {
game.InitializeGame()
for j := 0; !game.EndOfGame(); j = (j + 1) % playersCount {
game.MakePlay(j)
}
game.PrintWinner()
}
我可以将任何实现“GameImplementation”的实例用作“游戏”而无需任何转换:
var newGame Game
newGame = NewMonopolyGame() // implements GameImplementation
newGame.PlayOneGame(2)
更新:这样做的目的是尝试实现抽象基类的所有好处,而无需显式层次结构的所有耦合。如果我想定义一个新行为 PlayBestOfThreeGames,抽象基类将要求我更改基类本身 - 而这里我只是在 GameImplementation 接口之上再定义一个方法
【问题讨论】:
标签: syntax interface methods go