Inherited structure array in Go Lang

WBOY
Release: 2024-02-09 09:15:22
forward
1276 people have browsed it

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

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{}}
Copy after login

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 }
Copy after login

The following statements compile with this change:

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!