Pass method argument to function

后端 未结 2 1997
礼貌的吻别
礼貌的吻别 2020-11-29 05:52

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?

2条回答
  •  盖世英雄少女心
    2020-11-29 06:44

    You could also use the “method values” option listed by @icza with different receivers.

    package main
    
    import "fmt"
    
    type Foo int
    type Goo int
    
    func (f Foo) A() { fmt.Println("A") }
    func (f Foo) B() { fmt.Println("B") }
    func (g Goo) A() { fmt.Println("A") }
    
    func main() {
        //Method values with receiver f
        var f Foo
        bar2 := func(m func()) { m() }
        bar2(f.A) //A
        bar2(f.B) //B
        //Method values with receivers f and g
        var g Goo
        bar2(f.A) //A
        bar2(g.A) //A
    }
    

提交回复
热议问题