-1

Recently I have started building a chess game in GoLang and one issue I'm facing is storing different characters (i.e. Pawn, Knight, King) in a single array.

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

In the above case, can we have Knight and King in the same array since they are inherited from the same base class?

Like

characters := []character{Knight{}, King{}}
1
  • 4
    Knight and King are not inherited from the same base class because Go does not have inheritance. Consider using an interface type for the slice elements. Commented Jan 7, 2023 at 4:56

2 Answers 2

2

Use basic interfaces for 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 }

The following statement compiles with this changes:

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

Also, you probably want pointer receivers as in this example.

Sign up to request clarification or add additional context in comments.

Comments

2

Go doesn't have classes and inheritance. Compile-time polymorphism is not possible in Go (since method overloading is not supported). It only has Runtime Polymorphism. But it has a concept called composition. Where the struct is used to form other objects.

You can read here why Golang doesn't have inheritance like OOP concepts in other programming languages. https://www.geeksforgeeks.org/inheritance-in-golang/

OR

Instead of implementing chess pieces separately, you can have single struct for all of them with different values of respective attributes.

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

OR

You must use interface if you want to implement chess pieces separately.

1 Comment

Thanks for pointing out. I meant "Go doesn't have polymorphism" in pure polymorphism essence. Compile-time polymorphism is not possible in Go. (since method overloading is not supported) It only has Runtime Polymorphism. Updating my answer accordingly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.