面试题答案
一键面试package main
import (
"fmt"
)
// Handler 接口定义
type Handler interface {
Handle()
}
// Dispatch 函数实现
func Dispatch(data interface{}) {
if handler, ok := data.(Handler); ok {
handler.Handle()
} else {
fmt.Println("类型断言失败,该类型未实现 Handler 接口")
}
}
// 定义一个未命名类型并实现 Handler 接口
type customType struct{}
func (ct customType) Handle() {
fmt.Println("customType 的 Handle 方法被调用")
}
你可以这样调用:
func main() {
var data interface{}
data = customType{}
Dispatch(data)
data = "not a Handler type"
Dispatch(data)
}
在上述代码中:
- 定义了
Handler
接口,包含Handle
方法。 Dispatch
函数接收一个空接口类型参数,通过类型断言判断传入的参数是否实现了Handler
接口,如果实现了则调用Handle
方法,否则打印类型断言失败的提示。- 定义了一个未命名类型
customType
并实现了Handler
接口的Handle
方法。 - 在
main
函数中,分别使用实现了Handler
接口的类型和未实现该接口的类型调用Dispatch
函数,展示其处理逻辑。