Go Lang中继承结构的数组



最近我开始在GoLang中创建一个国际象棋游戏,我面临的一个问题是在单个数组中存储不同的字符(即Pawn, Knight, King)。

package main
import "fmt"
type character struct {
currPosition [2]int
}
type Knight struct {
c character
}
func (K Knight) Move() {
fmt.Println("Moving Kinght...")
}
type King struct {
c character
}
func (K King) Move() {
fmt.Println("Moving King...")
}

在上面的情况下,我们可以有骑士和国王在同一个数组,因为他们是从同一个基类继承的?

characters := []character{Knight{}, King{}}

使用基本接口实现多态性

type character interface {
Move()
Pos() [2]int
}
type Knight struct {
pos [2]int
}
func (K *Knight) Move() {
fmt.Println("Moving Kinght...")
}
func (k *Knight) Pos() [2]int { return k.pos }
type King struct {
pos [2]int
}
func (k *King) Move() {
fmt.Println("Moving King...")
}
func (k *King) Pos() [2]int { return k.pos }

下面的语句编译时会有这样的变化:

characters := []character{&Knight{}, &King{}}

同样,你可能需要像这个例子中那样的指针接收器。

Go没有类和继承。编译时多态性在Go中是不可能的(因为不支持方法重载)。它只有运行时多态性。但它有一个概念叫做合成。

您可以在这里阅读为什么Golang不像其他编程语言中的OOP概念那样具有继承。https://www.geeksforgeeks.org/inheritance-in-golang/

与单独实现棋子不同,您可以为所有棋子提供具有不同属性值的单个结构。

// Piece represents a chess piece
type Piece struct {
Name   string
Color  string
PosX   int
PosY   int
Moves  int
Points int
}
type Board struct {
Squares [8][8]*Piece
}
func (b *Board) MovePiece(p *Piece, x, y int){
// Your logic to move a chess piece.
}
...
// and make objects for Piece struct as you build the board.
king := &Piece{Name: "King", Color: "White", Points: 10}

如果要单独实现棋子,必须使用接口。

最新更新