我有以下结构:
type Foo struct {
Bar func(foo *Foo) bool
}
因为Bar
实际上不是一个方法,所以它接受Foo
作为参数(如Python绑定方法中的self
)。然而,如果有一个简单的方法,我会将它绑定到结构作为方法。我怀疑我可以使用反射,但我想保持它的微不足道。是否有将函数绑定到结构的技巧?你会怎么做?
编辑:我将添加一个我正在做的具体示例。
type Route struct {
Matcher func(route *Route, r *http.Request) bool
}
路由接受自定义Matcher
功能。如果未设置,则在注册路径时设置默认匹配器功能:
func (mux *ServeMux) HandleRoute(r Route) {
// ...
// Set default matcher.
if r.Matcher == nil {
r.Matcher = mux.RouteMatcher
}
// ...
}
然后该函数用于进行匹配:
func (mux *ServeMux) Match(r *http.Request) Route {
// ...
if route.Matcher(&route, r) {
...
}
...
}
该功能未绑定到路线。我的问题是,如果这是设置自定义可调用的合理/惯用方法,或者是否有一个技巧使函数“绑定”到结构作为方法。
答案 0 :(得分:2)
答案 1 :(得分:2)
无法在运行时绑定新方法。编译器需要知道类型在编译时具有哪些方法。请考虑以下代码:
package main
import "rand"
type Foo struct {}
type Bar interface {
Baz()
}
func main() {
if rand.Intn(2) != 0 {
// code to bind method Baz to Foo at runtime
}
var f Foo
// Should this compile? It depends on whether or not the if
// statement above ran, which can only be known at runtime.
f.Baz()
// Same here. The compiler can't know whether or not f has
// a method Baz.
var b Bar = f
}
您的示例代码看起来是一种合理的方式来执行您想要的操作。 PeterSO的答案提出了另一种方法,使函数看起来更像常规方法。
答案 2 :(得分:0)
如何创建一个具有所需名称(Bar
)的辅助方法,该方法在运行时选择并调用所需的函数?