我很好奇Go是否可行.我有一个有多种方法的类型.有可能有一个函数,它接受一个方法,并可以为该类型调用它?
这是我想要的一个小例子:
package main
import (
"fmt"
)
type Foo int
func (f Foo) A() {
fmt.Println("A")
}
func (f Foo) B() {
fmt.Println("B")
}
func (f Foo) C() {
fmt.Println("C")
}
func main() {
var f Foo
bar := func(foo func()) {
f.foo()
}
bar(A)
bar(B)
bar(C)
}
Run Code Online (Sandbox Code Playgroud)
Go think类型Foo有一个名为的方法foo(),而不是用传入的方法名称替换它.
我可以为常用方法创建方法别名:
func method1() {
fmt.Println("method1")
}
var Method1 = method1
Run Code Online (Sandbox Code Playgroud)
但是对于方法接收器不能做同样的事情:
type Person struct {
Name string
}
func (p *Person) methodReciver() {
fmt.Println("method reciver")
}
var MethodReciver = methodReciver
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我得到了错误在线var MethodReciver = methodReciver:
undefined: methodReciver
Run Code Online (Sandbox Code Playgroud)
完整代码:
package main
import (
"fmt"
)
type Person struct {
Name string
}
func method1() {
fmt.Println("method1")
}
var Method1 = method1
func (p *Person) methodReceiver() {
fmt.Println("method receiver")
}
var MethodReceiver = methodReceiver
func main() {
method1()
Method1()
p := …Run Code Online (Sandbox Code Playgroud)