Interface types
An interface type specifies a set of methods that a concrete type must possess to be considered an instance of that interface.
An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface. The value of an uninitialized variable of interface type is nil.
Here is a go lang example that shows how to use an interface.
Source: (example.go)
package main
import "fmt"
type Pet interface {
speak()
}
func speak(p Pet) {
p.speak()
}
type Cat struct {
Pet
}
func (c Cat) speak() {
fmt.Println("I am a cat.")
}
type Dog struct {
Pet
}
func (d Dog) speak() {
fmt.Println("I am a Dog.")
}
func main() {
c := &Cat{}
speak(c)
d := &Dog{}
speak(d)
}
Output:
$ go run example.go
I am a cat.
I am a Dog.