首页 文章

使用反射生成Go方法集

提问于
浏览
-2

是否可以在运行时使用反射生成结构的接口或方法集?

例如:

type S struct {
    a int
}

func (s *S) Fn(b int) int {
    return s.a + b
}

type I interface {
    Fn(a int) int
}

func main() {
    var x I = &S{a: 5}
    fmt.Printf("%#v\n", x.Fn)
    fmt.Printf("%#v\n", reflect.TypeOf(x).Method(0))

    var y I
    y.Fn = x.Fn // This fails, but I want to set y.Fn at runtime.
    fmt.Printf("%#v\n", reflect.TypeOf(y).Method(0))
}

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

为了澄清,我正在尝试构建一个中间件库,所以接口我包含http处理程序,我想用每种处理器包含某种req / response日志记录,所以我需要返回一个新接口,我在新接口I中的每个函数包装原始的一些日志记录 .

1 回答

  • 0

    以下是接口I和J的处理方法 .

    type I interface { Fn1(a int) int }
    type J interface { Fn2(a int) int }
    
    type Y struct {       // Y implements I by calling fn
       fn func(a int) int
    }
    
    func (y Y) Fn1(a int) int { return y.fn(a) }
    
    type Z struct {       // Z implements J by calling fn
       fn func(a int) int
    }
    
    func (z Z) Fn2(a int) int { return y.fn(a) }
    
    var y I = Y{fn: x.Fn}
    var z J = Z{fn: x.Fn}
    

    没有必要使用反射 .

    playground example

相关问题