Answer the question
In order to leave comments, you need to log in
How to "inherit method" golang?
I made a simple code of two structures:
package main
import "fmt"
type Animal struct {
Name string
}
type Rabbit struct {
Animal
}
//Метод Walk у каждого свой
func (this *Animal) Walk() *Animal{
fmt.Println("I walk", this.Name)
return this
}
//Метод Say один
func (this *Animal) Say() *Animal{
fmt.Println("Im Animal and my Name is", this.Name)
return this
}
//Метод Walk изменяется для Rabbit и работает корректно
func (this *Rabbit) Walk() *Rabbit{
this.Animal.Walk()
fmt.Println("...and Jump")
return this
}
func main() {
animal := Animal{ Name: "Зверь" }
animal.Walk().Say().Walk()
fmt.Println("\n---------------------\n")
rabbit := Rabbit{ }
rabbit.Name = "Кроль"
rabbit.Walk().Say().Walk() // Say возвращает ссылку на Animal, поэтому второй вызов Walk срабатывает от Animal (без jump) - как сделать правильно?
}
Answer the question
In order to leave comments, you need to log in
package main
import "fmt"
type AnimalIntf interface {
Walk() AnimalIntf
Say() AnimalIntf
}
type Animal struct {
animal AnimalIntf
Name string
}
type Rabbit struct {
Animal
}
// Animal
func NewAnimal(name string) *Animal {
animal := new(Animal)
animal.animal = animal
animal.Name = name
return animal
}
//Метод Walk у каждого свой
func (this *Animal) Walk() AnimalIntf {
fmt.Println("I walk", this.Name)
return this.animal
}
//Метод Say общий
func (this *Animal) Say() AnimalIntf {
fmt.Println("Im Animal and my Name is", this.Name)
return this.animal
}
// Rabbit
func NewRabbit(name string) *Rabbit {
rabbit := new(Rabbit)
rabbit.animal = rabbit
rabbit.Name = name
return rabbit
}
//Метод Walk изменяется для Rabbit и работает корректно
func (this *Rabbit) Walk() AnimalIntf {
this.Animal.Walk()
fmt.Println("...and Jump")
return this.animal
}
func main() {
animal := NewAnimal("Зверь")
animal.Walk().Say().Walk()
fmt.Println("\n---------------------\n")
rabbit := NewRabbit("Кроль")
rabbit.Walk().Say().Walk()
}
I walk Зверь
Im Animal and my Name is Зверь
I walk Зверь
---------------------
I walk Кроль
...and Jump
Im Animal and my Name is Кроль
I walk Кроль
...and Jump
What you have done is called embed. You can move away from it explicitly and not be confused.
type Animal struct {
Name string
}
type Rabbit struct {
Ani Animal
}
func (this *Rabbit) Walk() *Rabbit{
this.Ani.Walk()
fmt.Println("...and Jump")
return this
}
func (this *Rabbit) Say() *Rabbit{
this.Ani.Say()
return this
}
rabbit := Rabbit{ }
rabbit.Ani.Name = "Кроль"
rabbit.Ani.Walk()
rabbit.Ani.Say()
rabbit.Ani.Walk()
This is called late binding (late binding) it is done simply through reflection, but it contradicts the idea of go.
stackoverflow.com/questions/10255926/go-reflection...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question