Ronna
Ronna

Reputation: 1190

Is it possible to dynamically create a function with a receiver (method) in go?

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.

Upvotes: 5

Views: 2693

Answers (1)

thwd
thwd

Reputation: 24828

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.


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

Upvotes: 7

Related Questions