Home  >  Article  >  Backend Development  >  Inherited structure array in Go Lang

Inherited structure array in Go Lang

WBOY
WBOYforward
2024-02-09 09:15:221294browse

Go Lang 中继承的结构体数组

Go Lang is a modern programming language that has quickly emerged in the programming world with its simplicity and efficiency. In Go Lang, structure is a common data type that can be used to organize and store a set of related data. However, in some cases, we may need to define an array containing multiple structures, operate on them and inherit from them. This article will introduce how to create and use inherited structure arrays in Go Lang to better cope with complex data structures and programming needs.

Question content

Recently I started building a chess game using golang and one problem I faced was 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 example, can we put knight and king in the same array since they inherit from the same base class?

like

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

Solution

Use Basic Interface as 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 statements compile with this change:

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

Additionally, you may need a pointer receiver like the one in this example.

The above is the detailed content of Inherited structure array in Go Lang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete