Simple application of go language interface

Time:2021-12-31

The polymorphic characteristics in go language are mainly realized through interfaces. For example, in the real world, mobile phones, cameras, USB drives, etc. can be plugged into the USB standard interface without worrying about which device the USB interface is provided for. The reason is that businesses comply with a USB standard when designing USB interfaces, such as size, cable arrangement, etc. if the computer uses USB as the input interface, So as long as it is a device that can be plugged into the interface, it can theoretically connect to the computer to work. This scenario is implemented in go language:

package main

import (
    "fmt"
)

//Define a USB interface that provides two methods
type USB interface {
    start()
    stop()
}

//Define the structure of a mobile phone
type phone struct {

}

//Let the mobile phone implement the two methods in the USB interface, and both of them must be implemented
func (p phone) start (){
    fmt.Println("phone start")
}

func (p phone) stop(){
    fmt.Println("phone stop")
}

//Define a camera structure
type camera struct {

}

//Let the camera also implement the two methods in the USB interface, and both of them must be implemented
func (c camera) start () {
    fmt.Println("camera start")
}

func (c camera) stop (){
    fmt.Println("camera stop")
}

//Define a computer structure
type computer struct {

}

//Define a member method of a computer. This method takes USB as the input interface, and this method starts two methods in the USB interface. It is not necessary to start both methods
func (c computer) working (u USB){
    u.start()
    u.stop()
}

func main(){

    phone := phone{}
    camera := camera{}
    computer := computer{}
    //As long as the device realizes the USB interface (the so-called realization of USB interface is to realize all the methods defined in the USB interface), it can start to work through the computer
    computer.working(phone)
    computer.working(camera)

}

Execution results:

phone start
phone stop
camera start
camera stop