最近,我开始在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{}}
2条答案
按热度按时间c7rzv4ha1#
使用polymorphism的基本接口。
下面的语句将使用此更改进行编译:
此外,您可能需要像本例中那样的指针接收器。
hwamh0ep2#
Go语言没有类和继承。编译时多态性在Go语言中是不可能的(因为不支持方法重载)。它只有运行时多态性。但是它有一个叫做组合的概念。结构体被用来形成其他对象。
您可以在这里了解为什么Golang没有像其他编程语言中的OOP概念那样的继承。https://www.geeksforgeeks.org/inheritance-in-golang/
或
不用单独实现棋子,您可以为所有棋子使用一个结构体,使其各自的属性具有不同的值。
或
如果要单独实现棋子,则必须使用接口。