创建对采用自我的方法的引用的集合的惯用方式是什么? [英] What is the idiomatic way to create a collection of references to methods that take self?
问题描述
我正在尝试将Python脚本转换为Rust,作为一种学习体验,并使该工具更快并缩小代码/可执行文件的大小.
I am trying to convert a Python script into Rust as a learning experience and to make the tool faster and shrink the size of the code/executable.
我当前正在尝试转换一个部分,该部分创建一个对self方法的引用列表.现在,我了解到没有一种方法可以为方法绑定 self
变量,必须使用闭包并关闭将调用该方法的对象.但是,当您创建一个闭包时,它会被分配一个唯一的匿名类型,因此我认为如果不对它们进行装箱,就无法创建一个 Vec
或闭包数组,这可能是可行的方法,但是具有一些不必要的开销.
I'm currently trying to convert a section that creates a list of references to methods on self. Now I've learned that there isn't a way to bind the self
variable for a method, one has to use a closure and close over the object that the methods will be called on. However when you create a closure it gets assigned a unique anonymous type, so I don't think I can create a Vec
or array of closures without boxing them, which might be the way to go, but has some overhead that might not be necessary.
我想知道的是,不是通过Python告知的方法引用列表的设计,还有一种更生锈的方法来做到这一点而不与类型系统作斗争吗?
What I'm wondering is, instead of the Python informed design of a list of method references, is there a more Rusty way to do this that doesn't fight the type system?
self.dataProcessors = []
if(self.dataMode) :
self.dataProcessors.append(self._processData_)
if(self.csvOn):
self.dataProcessors.append(self._processData_CSV_)
推荐答案
老实说,我不确定是否有一种 rusty 的方法,但是,是的,您可以使用相同的方法就像在Python中一样:
To be honest, I’m not sure about a more rusty way, but, yes, you can do it the same way as in Python:
struct Data;
impl Data {
fn foo(&self) {
println!("foo!");
}
fn bar(&self) {
println!("bar!");
}
}
fn main() {
let x: Vec<fn(&Data) -> ()> = vec![Data::foo, Data::bar];
let data = Data;
for f in x {
f(&data);
}
}
请注意,这与Python中的工作原理完全一样:您无需保留 self
,而是将其显式传递为now-function的第一个参数,该参数曾经是方法.
Note that this works exactly like in Python: instead of keeping self
, you explicitly pass it as the first argument of the now-function which used to be a method.
由于不需要存储任何值(如果使用闭包,则将是必需的),因此基本上您只拥有一个函数指针(类型为 fn(& Data)->()
,也就是函数类型,它采用 Data
并返回单位),因此它的大小是已知的,您不需要装箱.
Since there is no need to store any values (which would be necessary if you went with closures), basically all you have is a function pointer (of type fn(&Data) -> ()
, which is, well, the type of functions that take Data
and return unit), so its size is known and you don’t need boxing.
这篇关于创建对采用自我的方法的引用的集合的惯用方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!