接口
1,定义接口
在去语言中,接口是定义了类型一系列方法的列表,如果一个类型实现了该接口所有的方法,那么该类型就符合该接口
package 主要
import “fmt”
import “数学”
type Shape interface {
面积()float64
}
type Rectangle struct {
width float64
height float64
}
type Circle struct {
radius float64
}
func (r 矩形),区域(),float64 {
return r.height * r.width
}
func (c 圆),区域(),float64 {
return math.Pi *, math.Pow (c.radius, 2)
}
func getArea (shape 形状),float64 {
return shape.area ()
}
func main () {
r :=,矩形{20、10}
c :=,圆{4}
fmt.Println (“Rectangle Area =", getArea (r))
fmt.Println (“Circle Area =", getArea (c))
}//执行结果:
Rectangle Area =200
Circle Area =, 50.26548245743669 2,接口嵌入
package 主要
import “fmt”
import “数学”
type Shape interface {
面积()float64
}
type MultiShape interface {
Shape ,,,,,,,,,,,//嵌入式
}
type Rectangle struct {
width float64
height float64
}
type Circle struct {
radius float64
}
func (r 矩形),区域(),float64 {
return r.height * r.width
}
func (c 圆),区域(),float64 {
return math.Pi *, math.Pow (c.radius, 2)
}
func getArea (shape MultiShape), float64 {,,,,,,,//改为MultiShape
return shape.area ()
}
func main () {
r :=,矩形{20、10}
c :=,圆{4}
fmt.Println (“Rectangle Area =", getArea (r))
fmt.Println (“Circle Area =", getArea (c))
}//执行结果:
Rectangle Area =200
Circle Area 50.26548245743669=,,,,,,,,,//执行结果一致