Answer the question
In order to leave comments, you need to log in
How to inherit and override one method in GO?
There is some python code. Implemented via OOP.
class Animal:
def __init__(self, name):
self.name = name
def say(self):
print("My name is", self.name)
def eat(self):
print("My name is", self.name, "and i eat grass")
def walk(self):
print("My name is", self.name, "and i jump")
def start(self):
self.say()
self.eat()
self.walk()
class Shark(Animal):
def eat(self):
print("My name is", self.name, "and i eat seals")
def walk(self):
print("My name is", self.name, "and i swim in the ocean")
if __name__ == '__main__':
a = Animal("Kangaroo")
a.start()
print("------------------------")
s = Shark("Shark")
s.start()
Answer the question
In order to leave comments, you need to log in
Inheritance fails. There is no inheritance in Go.
Define the base type, embed it in the "successor" and override the desired method in the same place.
You can write something like this, it will be very similar)
package main
import "fmt"
// Doer do
type Doer interface {
eat()
}
// Animal is Animal
type Animal struct {
name string
}
func (animal *Animal) eat() {
fmt.Println("My name is", animal.name)
}
// Shark is Animal
type Shark struct {
Animal
}
func (shark *Shark) eat() {
fmt.Println("My name is", shark.name, "and i eat seals")
}
func start(doer Doer) {
doer.eat()
}
func main() {
animal := new(Animal)
animal.name = "Kangaroo"
start(animal)
fmt.Println("-----------------------")
shark := new(Shark)
shark.name = "Shark"
start(shark)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question