目录
接口调用
可以向接口变量赋值任何实现了该接口的类型的实例。然后通过接口变量调用接口的方法。而实际调用的方法该变量实际引用的实例的类型所定义的方法。这个特性称为多态。
package main
import "fmt"
type Shape interface {
GetArea() float64
GetPerimeter() float64
}
type Circle struct {
R float64
}
func (c Circle) GetArea() float64 {
fmt.Println("enter Circle.GetArea")
return 3.14 * c.R * c.R
}
func (c Circle) GetPerimeter() float64 {
return 3.14 * 2 * c.R
}
type Square struct {
W float64
H float64
}
func (s Square) GetArea() float64 {
fmt.Println("enter Square.GetArea")
return s.W * s.H
}
func (s Square) GetPerimeter() float64 {
return 2 * (s.W + s.H)
}
func main() {
var s Shape
s = Circle{10}
s.GetArea() // 输出:enter Circle.GetArea
s = Square{10, 10}
s.GetArea() // 输出:enter Square.GetArea
}