从接口检测基础类型
在Go程序中,有时候需要知道传过来的参数其底层的类型是什么,这可以通过一个类型开关器来完成。假设我们有两个结构体:
type Rembrandt struct{}
func (r Rembrandt) Paint() {}
type Picasso struct{}
func (r Picasso) Paint() {}
它们都实现了如下 Painter
接口:
type Painter interface {
Paint()
}
然后,我们可以用如下的类型选择器来检测底层类型:
func WhichPainter(painter Painter) {
switch painter.(type) {
case Rembrandt:
fmt.Println("The underlying type is Rembrandt")
case Picasso:
fmt.Println("The underlying type is Picasso")
default:
fmt.Println("Unknown type")
}
}
最后更新于
这有帮助吗?