Answer the question
In order to leave comments, you need to log in
How to implement an interface method with passing by reference?
Task: make different structures with a common method and add them to one array for iteration in a loop. In this case, the method must change the properties of the owner
. Two structures: Blinker and Jumper. The first can blink (has a color), the second can jump (has a height), but both can move (Move)
To move, I define the Movable interface and the Entity structure that implements this interface. In Blinker and Jumper I embed Entity
type Movable interface {
Move()
}
type Entity struct {
x, y int
}
func (e Entity) Move() {
e.x += 1
e.y += 1
}
type Blinker struct {
Entity
color string
}
type Jumper struct {
Entity
alt int
}
type Movers []Movable
var list Movers
func main() {
blinker := Blinker{color: "blue"}
jumper := Jumper{alt: 8}
list = append(list, blinker)
list = append(list, jumper)
for _, item := range list {
item.Move()
}
for _, item := range list {
fmt.Println(item)
// {{0 0} blue}
// {{0 0} 8}
}
}
func (e *Entity) Move() {}
// Blinker does not implement Movable (Move method has pointer receiver)
package main
import "fmt"
type Movers []Movable
type Movable interface {
Move()
}
type Entity struct {
x, y int
}
func (e Entity) Move() {
e.x += 1
e.y += 1
}
type Blinker struct {
Entity
color string
}
type Jumper struct {
Entity
alt int
}
var list Movers
func main() {
blinker := Blinker{color: "blue"}
jumper := Jumper{alt: 8}
list = append(list, blinker)
list = append(list, jumper)
for _, item := range list {
item.Move()
}
for _, item := range list {
fmt.Println(item)
// {{0 0} blue}
// {{0 0} 8}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question