I seem to be repeating the speak function for example.
Also is there a way to move the initial knowledge of the baby and the human to a default constructor instead of being passed while making a new baby and human?
package main
import (
"fmt"
)
func main() {
h := Human{"good things"}
d := Devil{}
b := Baby{"ga ga"}
b.speak()
h.speak()
d.poisons(&h)
d.poisons(&b)
b.speak()
h.speak()
}
type Human struct {
Knowledge string
}
type Devil struct{}
type Baby struct {
Knowledge string
}
type Knowledgable interface {
changeKnowledge(newKnowledge string)
}
func (d Devil) poisons(creature Knowledgable) {
creature.changeKnowledge(" evil things")
}
func (h Human) speak() {
fmt.Println(h.Knowledge)
}
func (b Baby) speak() {
fmt.Println(b.Knowledge)
}
func (h *Human) changeKnowledge(newKnowledge string) {
h.Knowledge += newKnowledge
}
func (b *Baby) changeKnowledge(newKnowledge string) {
b.Knowledge = newKnowledge
}
About speak() function you can embed
type Knowledge string
func (b Knowledge) speak() {
fmt.Println(b)
}
type Baby struct {
Knowledge
}
type Human struct {
Knowledge
}
and about constructors, seems for such a simple type buitin new() is OK but you can write an initializer
func Ini(k Knowledgable) {
switch k.(type) {
case *Baby:
k.changeKnowledge("ga-ga")
case *Human:
k.changeKnowledge("good things")
}
}
then things will be
h := new(Human)
b:=new(Baby)
Ini(h)
Ini(b)
h.speak()
if I didn't misunderstand, you want to make a "constructor" for the Baby and Human. There are some equivalents of constructors in Go.
If you have the Human struct:
type Human struct {
Knowledge string
}
You can call a function makeHuman
to create a new Human:
func makeHuman(knowledge string) Human {
return Human{knowledge}
}
If you prefer to return a pointer, you can choose this one:
func newHuman(knowledge string) *Human {
return &Human{knowledge}
}
You can check both options in the links below:
Using makeHuman
: https://play.golang.org/p/2hlTpnVXF9
Using newHuman
: https://play.golang.org/p/ru63o81C4V