在Go语言中,可以动态创建带有接收器(方法)的函数吗?

huangapple go评论125阅读模式
英文:

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).

huangapple
  • 本文由 发表于 2015年2月12日 23:28:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/28481354.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定