For a data type to match an interface, it must implement all the methods of that interface. For example:
package main
import "fmt"
// Action interface defines methods for a basic action
type Action interface {
performAction()
}
// Person structure representing an individual
type Person struct {
name string
}
// Animal structure representing an animal
type Animal struct {
species string
}
// Implementing methods for the Person type
func (p *Person) performAction() {
fmt.Printf("%s is speaking\n", p.name)
}
// Implementing methods for the Animal type
func (a *Animal) performAction() {
fmt.Printf("The %s is moving\n", a.species)
}
func performActionForEntity(entity Action) {
entity.performAction()
}
func main() {
john := &Person{name: "John"}
tiger := &Animal{species: "Tiger"}
performActionForEntity(john)
performActionForEntity(tiger)
}
In this example, we have an Action interface with a method performAction()
. The Person and Animal structures implement this interface by providing their respective implementations of the performAction()
method. The performActionForEntity
function demonstrates how an entity, whether a person or an animal, can perform its specific action.
In this case, the data type does not have to implement only the methods of the interface, you can define its methods for the data type, or also implement methods of other interfaces. For example:
package main
import "fmt"
// Speaker interface defines a method for speaking
type Speaker interface {
speak()
}
// Mover interface defines a method for moving
type Mover interface {
move()
}
func speakAndMove(entity Speaker, mover Mover) {
entity.speak()
mover.move()
}
// Person structure representing an individual
type Person struct {
name string
}
// Animal structure representing an animal
type Animal struct {
species string
}
// Implementing methods for the Person type
func (p *Person) speak() {
fmt.Printf("%s is speaking\n", p.name)
}
// Implementing methods for the Animal type
func (a *Animal) move() {
fmt.Printf("The %s is moving\n", a.species)
}
func main() {
john := &Person{name: "John"}
tiger := &Animal{species: "Tiger"}
speakAndMove(john, tiger)
}