doujia2090 2014-11-28 19:33
浏览 32

如何获取类型函数的方法字段(开始)

I'm wondering if it's possible to get the method fields from a typed function using reflection or by other means. The problem that I'm trying to solve is that I have a method which accepts a function of specific type but I need to actually transport different types and based on the type provided to execute operations. I'm aware that I could use an interface{} value as receiver but I don't want to loose the type checking on the calling function ("GetIt")

package main

type ttp struct {
    Coupons string
}

func (m ttp) GetIt(x string) {
    if m.Coupons != "" {
        print(m.Coupons)
    }
}

func calculate(mth func(s string)){
    //perform calculations and update the Coupon field
    mth.Cupons = "one coupon" // is not working :(
    // execute it again with the processed value
    mth.GetIt() // is not working


}
func main() {
    m := ttp{Coupons: "something"}
    calculate(m.GetIt)
}

Play

  • 写回答

1条回答 默认 最新

  • dsfsdfsdfsdf6455 2014-11-28 19:43
    关注

    well this does not answer your exact question but it should solve your problem and cleanup the logic: push the calculate method inside the type and use a interface

    https://play.golang.org/p/On_AigRYW6

    package main
    
    import "fmt"
    
    type Computer interface {
        Compute(string)
    }
    
    type myp struct {
        Coupons string
    }
    
    // myp implements Computer
    func (m *myp) Compute(x string) {
        m.GetIt(x)
        fmt.Println("myp")
    
    }
    
    type ttp struct {
        Various string
    }
    
    // ttp implements Computer
    func (m *ttp) Compute(x string) {
        m.GetIt(x)
        fmt.Println("ttp")
    }
    
    func (m myp) GetIt(x string) {}
    func (m ttp) GetIt(x string) {}
    
    func main() {
        m := &myp{Coupons: "something"}
        t := &ttp{Various: "various stuff"}
        var stuff = []Computer{m, t}
        for _, c := range stuff {
            c.Compute("s")
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化