【发布时间】:2021-09-30 11:55:02
【问题描述】:
假设我有一个名为 Hello 的接口,例如:
type Hello interface {
Hi() string
}
我想编写一个函数来获取Hello 和任何接口n 并在Hello 也实现n 接口时执行某些操作,例如:
type Person interface {
Name() int
}
type Animal interface {
Leg() int
}
type hello struct{}
func (h hello) Hi() string {
return "hello!"
}
func (h hello) Leg() int {
return 4
}
func worker() {
h := hello{}
// Doesn't match
check(h,(Person)(nil))
// Matches
check(h,(Animal)(nil))
}
func check(h Hello, n interface{}) {
// of course this doesn't work, should I use reflection, if so how?
if _,ok := h.(n); ok {
// do something
}
}
check函数如何实现?
【问题讨论】:
标签: go reflection