golang interface接口
package main import "fmt" type Shaper interface { Area() float32 } type Square struct { side float32 } func (sq *Square) Area() float32 { return sq.side * sq.side } func main() { sq1 := new(Square) sq1.side = 5 var areaIntf Shaper areaIntf = sq1 // shorter,without separate declaration: // areaIntf := Shaper(sq1) // or even: // areaIntf := sq1 fmt.Printf("The square has area: %fn",areaIntf.Area()) }
上面的程序定义了一个结构体? 在? 所以可以将一个? 现在接口变量包含一个指向? 这是?多态?的 Go 版本,多态是面向对象编程中一个广为人知的概念:根据当前的类型选择正确的方法,或者说:同一种类型在不同的实例上似乎表现出不同的行为。 如果? cannot use sq1 (type *Square) as type Shaper in assignment: *Square does not implement Shaper (missing Area method) 如果? 扩展一下上面的例子,类型? package main import "fmt" type Shaper interface { Area() float32 } type Square struct { side float32 } func (sq *Square) Area() float32 { return sq.side * sq.side } type Rectangle struct { length,width float32 } func (r Rectangle) Area() float32 { return r.length * r.width } func main() { r := Rectangle{5,3} // Area() of Rectangle needs a value q := &Square{5} // Area() of Square needs a pointer // shapes := []Shaper{Shaper(r),Shaper(q)} // or shorter shapes := []Shaper{r,q} fmt.Println("Looping through shapes for area ...") for n,_ := range shapes { fmt.Println("Shape details: ",shapes[n]) fmt.Println("Area of this shape is: ",shapes[n].Area()) } } 在调用? 在调用? package main import "fmt" type stockPosition struct { ticker string sharePrice float32 count float32 } /* method to determine the value of a stock position */ func (s stockPosition) getValue() float32 { return s.sharePrice * s.count } type car struct { make string model string price float32 } /* method to determine the value of a car */ func (c car) getValue() float32 { return c.price } /* contract that defines different things that have value */ type valuable interface { getValue() float32 } func showValue(asset valuable) { fmt.Printf("Value of the asset is %fn",asset.getValue()) } func main() { var o valuable = stockPosition{"GOOG",577.20,4} showValue(o) o = car{"BMW","M3",66500} showValue(o) } 数据类型实现了接口,就能使用以接口变量为参数的方法 备注: 有的时候,也会以一种稍微不同的方式来使用接口这个词:从某个类型的角度来看,它的接口指的是:它的所有导出方法,只不过没有显式地为这些导出方法额外定一个接口而已。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |