英文:
Is it possible to dynamically create a function with a receiver (method) in go?
问题
我正在阅读关于reflect.MakeFunc的内容,并想知道是否有办法在运行时创建一个带有接收器的Method(一个带有接收器的函数)。
英文:
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.
答案1
得分: 5
不,这是不可能的,因为如果这样做,接收者的类型方法集会在运行时发生变化。正如你所知,Go 在当前的实现中是在编译时进行类型检查的。如果一个类型在运行时突然获取(或失去)方法,你需要在每个接受接口参数的函数调用上进行运行时接口实现检查。
在运行时创建一个带有接收者的方法(函数)
从技术上讲,你可以通过分叉 reflect 包来构建一个表示附加到任意类型的方法的值。然而,这不会改变该类型的方法集,因为它本质上是绕过 Go 类型系统的一种方法。
关于在对象上交换方法指针呢?
与 Java 不同,Go 在具体值中不嵌入虚拟方法分派表,只在接口值中嵌入。如果你愿意动手,你可以获取一个 reflect.nonEmptyInterface
并修改它的 itable(itab 字段)。
英文:
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
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.
<hr>
> What about swapping method pointers on an object?
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论