我有一个界面如下:
type visitable interface {
getName() string
getLookupMessage() string
}
我想用
apply(visitable []visitable, function ???)
之类的签名创建一个函数接受可访问的函数(例如 getName 或 getLookupMessage)作为第二个参数。我可以在技术上做到这一点吗?如果是,如何?
最佳答案
是的,在这种特定情况下,您可以使用 method expressions .这是因为两个接口(interface)方法具有相同的签名,即两个 visitable.getName
的类型。和 visitable.getLookupMessage
是 func(visitable) string
:
package main
type visitable interface {
getName() string
getLookupMessage() string
}
func apply(vs []visitable, m func(visitable) string) {
for _, v := range vs {
m(v)
}
}
func main() {
apply(nil, visitable.getName)
apply(nil, visitable.getLookupMessage)
}
但是,考虑到
apply
的琐碎程度就是,尚不清楚为什么这会有用,尤其是考虑到这不适用于具有不同签名的方法。
关于go - 如何将接口(interface)方法传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60117668/