我正在阅读有关 reflect.MakeFunc 的信息,想知道是否还有一种创建方法在运行时使用方法(带有接收器的函数).
I was reading about reflect.MakeFunc and was wondering if there's also a way to create a Method (a function with a receiver) at runtime.
推荐答案否,这是不可能的,因为接收方的类型如果这样做,方法会在运行时更改.如您所知,Go的当前实现在编译时进行了类型检查.如果类型可能在运行时突然获取(或丢失)方法,则需要对使用接口参数的每个函数调用进行运行时接口实现检查.
No, this is not possible because the receiver's type method set would change on runtime if you did this. As you may know, Go in its current implementations is type checked at compile time. You would require runtime interface-implementation checks on every function-call that takes an interface argument if a type could suddenly acquire (or lose) methods at runtime.
在运行时创建方法(带有接收器的函数)的方法
a way to create a Method (a function with a receiver) at runtime
但是,从技术上讲,您可以 通过派生reflect包来构建一个表示附加到任意类型的方法的值.但是,这不会更改所述类型的方法集,因为它实际上是对Go的类型系统的一种破解.
Technically, though, you could build a value representing a method attached to an arbitrary type by forking the reflect package. This would not, however, change said type's method set because it'd be essentially a hack around Go's type system.
在对象上交换方法指针该怎么办?
What about swapping method pointers on an object?
开始,不像例如Java不会将虚拟方法分派表嵌入具体值中,仅在接口值中.如果您愿意动手,则可以持有 reflect.nonEmptyInterface 并修改其 itable (itab字段).
Go, unlike e.g. Java does not embed a virtual method dispatch table in concrete values, only in interface values. If you're willing to get your hands dirty you could get a hold of a reflect.nonEmptyInterface and modify its itable (itab field).
更多推荐
是否可以使用接收器(方法)动态创建函数?
发布评论