>

Interface

In Go, there is a powerful, and dreaded word… Interface.

Interfaces can provide flexability.

Animal, Dog & Cat

For an example, I’ve got the interface, and 2 structures…

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
type Animal interface {
    Name() string
    Sound() string
}

type Dog struct {
    name string
}

func (d *Dog) Name() string {
    return d.name
}

func (d *Dog) Sound() string {
    return "woof"
}

type Cat struct {
    name string
}

func (c *Cat) Name() string {
    return c.name
}

func (c *Cat) Sound() string {
    return "meow"
}

Now using this…

1
2
3
4
5
6
7
8
9
import "fmt"

func main() {
    var a1 Animal = &Dog{name: "Spot"}
    var a2 Animal = &Cat{name: "Rex"}

    fmt.Printf("%s says %s\n", a1.Name(), a1.Sound())
    fmt.Printf("%s says %s\n", a2.Name(), a2.Sound())
}

Please note how I made those 2 Animals.

In Go, an interface (in this case Animal), must have a Pointer (in this case, a pointer to a Dog, and a pointer to a Cat, in Go, they would be represented as *Dog and *Cat).

Once it is an Animal, you must use reflect to convert it from Animal to *Dog or *Cat


2023-11-09