Member-only story

Introduction
interface
I would like people who are studying the Go language to read it because it is difficult to understand when it gets involved.
In particular, Tour of Go of Stringers assumes that you no longer know as per se.
Also, since the purpose is to deepen the understanding compared to Java, I think it will be a piercing explanation for those who have experience with Java.
Why I don’t understand
I think there are two causes.
- I don’t understand the concept of interface well in the first place
- I misunderstand that an explicit implementation is a prerequisite
The former does not know that completely different types (classes) can be treated as interface types and partly the same.
The latter is confused about how to write Go because he thinks too much about Java’s explicit interface implementation.
I think that’s what it means.
Implementation example of an interface (Theme: What does eating mean?)
package mainimport "fmt"// Interface for eating
type Eater interface {
PutIn () // Put in your mouth
Chew () // chew
Swallow () // swallow
}
// Human structure
type Human struct {
Height int // Height int //
}
// Turtle structure
type Turtle struct {
Kind string // Type
}// Implementation of human interface
func (h Human) PutIn () {
fmt.Println ("Use a tool carefully")
}
func (h Human) Chew () {
fmt.Println ("bite firmly with teeth")
}
func (h Human) Swallow () {
fmt.Println ("If you chew well, swallow")
}// Implementation of interface for turtles
func (h Turtle) PutIn () {
fmt.Println ("If you find a prey, quickly stretch your neck and bite")
}
func (h Turtle) Chew () {
fmt.Println ("Crush with a beak")
}
func (h Turtle) Swallow () {
fmt.Println ("If you crush it into small pieces, swallow it")
}// Eating method with interface as an argument
func EatAll (e Eater) {
e.PutIn () // Call from interface
e.Chew ()
e.Swallow ()
}