dongwei3151 2017-09-12 21:24
浏览 187
已采纳

在Go中,是否可以有一个指向带参数的成员函数/方法的指针?

If I have

type Foo struct {
    // some data
}

func (f *Foo) Op1() bool {
    // perform operation and return a bool
}

func (f *Foo) Op2(other int) bool {
    // perform a different operation using internal data
    // and the passed in parameter(s)
}

I know I can store a pointer to the first method.

fn := f.Op1

and call it

if fn(f) { // do something }

But what if I want to do the same with Op2? I am currently faking it by defined a wrapper function which takes a Foo and the values and calls the operation. But that is a lot of boiler plate code.

  • 写回答

1条回答 默认 最新

  • dtgta48604 2017-09-12 21:29
    关注

    Using method expressions

    In this case, we get a reference from the type, then you need to pass an instance as the first argument.

    fn2 := (*Foo).Op2
    f := &Foo{}
    fn2(f, 2)
    

    Referencing an instance method

    In this case, the instance is already bind to the method and you can just provide the arguments:

    fn2 := f.Op2
    fn2(2)
    

    Playground: https://play.golang.org/p/e0gUIHzj7Z

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?