go语言中的多态个性次要是通过接口来实现的,例如在事实世界中能够把手机,相机,U盘等插到USB标准接口上,而不必放心该USB接口是为哪种设施提供的,起因是商家在设计USB接口时都恪守了一个USB规范,如尺寸,排线等,如果电脑将USB作为输出接口,那么只有是可能插到该接口的设施实践上都能够连贯电脑进行工作。上面通过Go语言实现这种场景:

package mainimport (    "fmt")//定义一个USB接口,该接口提供两个办法type USB interface {    start()    stop()}//定义一个手机的构造体type phone struct {}//让手机实现USB接口中的两个办法,且必须都要实现func (p phone) start (){    fmt.Println("phone start")}func (p phone) stop(){    fmt.Println("phone stop")}//定义一个相机构造体type camera struct {}//让相机也实现USB接口中的两个办法,且必须都要实现func (c camera) start () {    fmt.Println("camera start")}func (c camera) stop (){    fmt.Println("camera stop")}//定义一个电脑构造体type computer struct {}//定义一个电脑的成员办法,该办法将USB作为输出接口,并且该办法启动USB接口中的两个办法,不是必须都要将两个启动func (c computer) working (u USB){    u.start()    u.stop()}func main(){    phone := phone{}    camera := camera{}    computer := computer{}    //只有是实现了USB接口(所谓实现USB接口就是实现了USB接口中定义的所有办法)的设施,都能够通过电脑启动工作    computer.working(phone)    computer.working(camera)}

执行后果:

phone startphone stopcamera startcamera stop