Anonymous Interface in Golang

336 阅读1分钟

We can define a struct, which has a field with type of interface, such as below,

package main

import "fmt"

type Vehicle interface {
	Print()
}

type Car struct {
	Name string
}

func (c *Car) Print() {
	fmt.Println(c.Name)
}

type Suv struct {
	Name string
}

func (s *Suv) Print() {
	fmt.Println(s.Name)
}

type Task struct {
	v Vehicle
}

func main() {
	t := Task{}
	t.v = &Car{Name: "car"}
	t.v.Print()

	t.v = &Suv{Name: "suv"}
	t.v.Print()
}

The Task struct has a field named v with type Vehicle, then we can call t.v.Print() to execute some logic. Anonymous interface embedded in struct can simplify the above function to make it cleaner,

package main

import "fmt"

type Vehicle interface {
	Print()
}

type Car struct {
	Name string
}

func (c *Car) Print() {
	fmt.Println(c.Name)
}

type Suv struct {
	Name string
}

func (s *Suv) Print() {
	fmt.Println(s.Name)
}

type Task struct {
	Vehicle
}

func main() {
	t := Task{}
	t.Vehicle = &Car{Name: "car"}
	t.Print()

	t.Vehicle = &Suv{Name: "suv"}
	t.Print()
}

This time we define a Vehicle interface directly in Task struct, calling t.Print() become cleaner.