将方法参数传递给函数 [英] Pass method argument to function

查看:76
本文介绍了将方法参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇这在Go中是否可行.我有多种方法的类型.

I'm curious if this is possible in Go. I have a type with multiple methods. Is it possible to have a function which takes a method argument and then call it for the type?

这是我想要的一个小例子:

Here is a small example of what I would want:

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)
}

Go认为类型Foo具有一个名为foo()的方法,而不是将其替换为传入的方法名称.

Go thinks type Foo has a method called foo(), rather than replacing it with the passed in method name.

推荐答案

是的,有可能.您有2(3)个选项:

Yes, it's possible. You have 2 (3) options:

表达式Foo.A产生与A等效的函数,但是第一个参数是显式接收者;它具有签名func(f Foo).

The expression Foo.A yields a function equivalent to A but with an explicit receiver as its first argument; it has signature func(f Foo).

var f Foo
bar := func(m func(f Foo)) {
    m(f)
}
bar(Foo.A)
bar(Foo.B)
bar(Foo.C)

这里方法的接收者是显式的.您只需将方法名称(具有它的类型)传递给bar(),并且在调用它时,您必须传递实际的接收者:m(f).

Here the method receiver is explicit. You only pass the method name (with the type it belongs to) to bar(), and when calling it, you have to pass the actual receiver: m(f).

按预期输出(在转到操场上尝试):

Output as expected (try it on the Go Playground):

A
B
C

规范:方法值

如果f是类型Foo的值,则表达式f.A会产生类型func()的函数值,其中包含隐式接收者值f.

Spec: Method values

If f is a value of type Foo, the expression f.A yields a function value of type func() with implicit receiver value f.

var f Foo
bar := func(m func()) {
    m()
}
bar(f.A)
bar(f.B)
bar(f.C)

请注意,这里的方法接收器是隐式的,它与传递给bar()的函数值一起保存,因此在未显式指定它的情况下调用它:m().

Note that here the method receiver is implicit, it is saved with the function value passed to bar(), and so it is called without explicitly specifying it: m().

输出是相同的(在转到游乐场上尝试).

Output is the same (try it on the Go Playground).

不如以前的解决方案(在性能和安全性"上),但是您可以将方法的名称作为string值传递,然后使用

Inferior to previous solutions (both in performance and in "safeness"), but you could pass the name of the method as a string value, and then use the reflect package to call the method by that name. It could look like this:

var f Foo
bar := func(name string) {
    reflect.ValueOf(f).MethodByName(name).Call(nil)
}
bar("A")
bar("B")
bar("C")

去游乐场上尝试一下.

这篇关于将方法参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆