Go语言中继承的结构体数组

dced5bon  于 2023-01-10  发布在  Go
关注(0)|答案(2)|浏览(123)

最近,我开始在GoLang中构建一个国际象棋游戏,我面临的一个问题是在一个数组中存储不同的字符(即兵、骑士、国王)。

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...")
}

在上面的例子中,我们可以在同一个数组中有Knight和King吗?因为它们是从同一个基类继承的。
喜欢

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

c7rzv4ha1#

使用polymorphism的基本接口。

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{}}

此外,您可能需要像本例中那样的指针接收器。

hwamh0ep

hwamh0ep2#

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}


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

相关问题