是否可以使用接收器(方法)动态创建函数? [英] Is it possible to dynamically create a function with a receiver (method) in go?

查看:40
本文介绍了是否可以使用接收器(方法)动态创建函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关 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.

推荐答案

否,这是不可能的,因为接收方的类型

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不会将虚拟方法分派表嵌入具体值中,仅在接口值中.如果您愿意动手,则可以持有

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

这篇关于是否可以使用接收器(方法)动态创建函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆