是否可以通过反射在运行时生成结构体的接口(interface)或方法集?
例如:
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_
为了澄清,我正在尝试构建一个中间件库,以便接口(interface)包含 http 处理程序,并且我想用某种请求/响应日志记录来包装每个处理程序,因此我需要返回一个新接口(interface) I,其中每个函数都在新界面我包装了原始界面 + 一些日志记录。
最佳答案
下面是接口(interface) 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}
不需要使用反射。
关于go - 使用反射生成Go方法集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40332011/