关于golang:Go语言接口interface简单应用

2次阅读

共计 886 个字符,预计需要花费 3 分钟才能阅读完成。

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

package main

import ("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 start
phone stop
camera start
camera stop
正文完
 0