3.8 Interface 接口

优质
小牛编辑
112浏览
2023-12-01

Interface接口

  这一章我们要讲解一下Go的另外一个重要类型——接口类型。

  Go 语言不是一种 “传统” 的面向对象编程语言:它里面没有类和继承的概念。但是 Go 语言里有非常灵活的接口概念,通过它可以实现很多面向对象的特性。

接口定义

普通定义形式:

type Interface Shape{  //最普通的形式
    Area() float64
}

空接口定义:

空接口,即 interface{},可以代表任何类型,有点类似于 java 中的 Object 类可以作为任何形参和返回类型。

func test( i int ) interface{} {
  if i ==  0 {
    return "hello"
  }
  return i;
}

这里例子中,由于有可能返回string,也有可能返回int,因此将返回值设置成为interface,这个在Go的package包中会大量见到。

类型不需要显式声明它实现了某个接口:接口被隐式地实现,多个类型可以实现同一个接口。只要类型实现了接口中的方法,它就实现了此接口。

pro03_8_1.go

//接口定义
type Shape interface {
    Area() float64 //求面积
}

//圆形定义
type Circle struct {
    radius float64
}

//圆形面积计算
func (this Circle) Area() float64 {
    return math.Pi * this.radius * this.radius
}

//矩形定义
type Rectangle struct {
    length  float64
    width float64
}

//矩形面积计算
func (this Rectangle) Area() float64 {
    return this.length * this.width
}
func main() {
    var circle Circle
    circle.radius = 3
    fmt.Println(circle.Area())

    rec := Rectangle{5.0, 8}
    fmt.Println(rec.Area())
}

接口嵌套接口

接口可以包含其他接口.

type ShapeArea interface {
    Area() float64 //求面积
}
type ShapePerimeter interface{
    Perimeter() float64 //    求周长
}
type Shape interface{
    ShapeArea
    ShapePerimeter
}

详细情况看pro03_8_2.go

//面积接口
type ShapeArea interface {
    Area() float64 //求面积
}

//周长接口
type ShapePerimeter interface {
    Perimeter() float64 //    求周长
}

//形状接口:包含面积接口、周长接口
type Shape interface {
    ShapeArea
    ShapePerimeter
}

//圆形定义
type Circle struct {
    radius float64
}

//实现圆形面积接口
func (this Circle) Area() float64 {
    return math.Pi * this.radius * this.radius
}

//实现圆形周长接口
func (this Circle) Perimeter() float64 {
    return 2 * math.Pi * this.radius
}

func main() {
    var circle Circle
    circle.radius = 3
    fmt.Println("Cirle area:", circle.Area())
    fmt.Println("Cirle perimeter:", circle.Perimeter())
}

检测对象是否实现了接口的方法

    var circle Circle
    circle.radius = 3
    var s Shape = circle
    if circleValue, ok := s.(ShapePerimeter); ok {
        fmt.Printf("circle implements Perimeter(): %f\n", circleValue.Perimeter())
    }

通过上面的例子,我们可以看出Shape接口实现了ShapePerimeter接口