是否可以使用接收器(方法)动态创建函数?

编程入门 行业动态 更新时间:2024-10-15 18:29:58
本文介绍了是否可以使用接收器(方法)动态创建函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

是否可以使用接收器(方法)动态创建函数?

本文发布于:2023-11-25 02:18:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627923.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接收器   可以使用   函数   方法   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!