Go 使用类型断言来检查传入的对象是否实现了特定接口

33 min read

在 Go 中,可以使用类型断言来检查传入的对象是否实现了特定接口。类型断言使用 .(Type) 的语法,其中 Type 是要检查的接口类型。

下面是一个简单的示例代码:

package main

import (
	"fmt"
)

type Shape interface {
	Area() float64
}

type Circle struct {
	radius float64
}

func (c Circle) Area() float64 {
	return 3.14 * c.radius * c.radius
}

type Rectangle struct {
	length, width float64
}

func (r Rectangle) Area() float64 {
	return r.length * r.width
}

func printArea(s Shape) {
	if _, ok := s.(Shape); ok {
		fmt.Println("Implement Shape interface")
		fmt.Println("Area:", s.Area())
	} else {
		fmt.Println("Does not implement Shape interface")
	}
}

func main() {
	circle := Circle{radius: 5}
	rectangle := Rectangle{length: 5, width: 10}

	printArea(circle)
	printArea(rectangle)
}

在上面的代码中,我们定义了一个 Shape 接口,并实现了两个结构体 CircleRectangle,它们都实现了 Shape 接口中的 Area 方法。

printArea 函数使用类型断言 s.(Shape) 来检查传入的对象 s 是否实现了 Shape 接口。如果实现了该接口,我们可以调用 s.Area() 方法来计算其面积;否则,打印出 "Does not implement Shape interface"。

运行上述代码,将输出:

Implement Shape interface
Area: 78.5
Implement Shape interface
Area: 50

这表明传入的 circlerectangle 对象都实现了 Shape 接口,并成功地计算出了它们的面积。