go接口
1、go通过接口将所有共性的方法进行统一处理,类比理解c++的多态
2、interface可以类比为protocal,理解为双方为交流而做出的约定
3、interface是golang里面的抽象类型(类型的一种)!!!
//定义接口
type AirIF interface {
fly()
}
//定义结构体
type bird struct{
}
//定义结构体
type human struct{
}
//注:两个结构体bird、human都有接口里所有方法的共有属性
//examp:
func (bird)fly(){
}
func (human)fly(){
}
转自:https://www.runoob.com/go/go-interfaces.html
package main import ( "fmt" ) type Phone interface { call() } type NokiaPhone struct { } func (nokiaPhone NokiaPhone) call() { fmt.Println("I am Nokia, I can call you!") } type IPhone struct { } func (iPhone IPhone) call() { fmt.Println("I am iPhone, I can call you!") } func main() { var phone Phone phone = new(NokiaPhone) phone.call() phone = new(IPhone) phone.call() } 编译: I am Nokia, I can call you! I am iPhone, I can call you!
package main import ( "fmt" "math" ) type geometry interface { area() float64 perim() float64 } type rect struct { width, height float64 } type circle struct { radius float64 } func (r rect) area() float64 { return r.width * r.height } func (r rect) perim() float64 { return 2*r.width + 2*r.height } func (c circle) area() float64 { return math.Pi * c.radius * c.radius } func (c circle) perim() float64 { return 2 * math.Pi * c.radius } func measure(g geometry) { fmt.Println(g) fmt.Println(g.area()) fmt.Println(g.perim()) } func main() { r := rect{width: 3, height: 4} c := circle{radius: 5} measure(r) measure(c) } 编译: {3 4} 12 14 {5} 78.53981633974483 31.41592653589793
懵懵懂懂,难得糊涂!
潜心所向,无关风月!
浙公网安备 33010602011771号