如何映射到结构方法?

Chu*_*son 0 rust

我正在尝试使用结构方法作为地图目标。当我尝试仅通过“self.method”引用映射参数中的方法时,出现错误“方法,而不是字段”。

这是一些简单的代码来展示我想要做什么

impl Astruc {
    fn map_function(&self, index: usize) -> usize {
        2 * index
    }
    fn map_attempt(&self) {
        (0..10).map(self.map_function)  // this causes the error: method, not a field
    }
}
Run Code Online (Sandbox Code Playgroud)

如何正确参考map_function

hev*_*ev1 6

要调用实例上的方法,可以使用闭包。

fn map_attempt(&self) {
    (0..10).map(|i| self.map_function(i))
        .for_each(|i| println!("{i}"));
}
Run Code Online (Sandbox Code Playgroud)

但是,如果map_function实际上不需要在实例上调用,则可以使用结构名称或Self(删除self参数后)来引用它。

impl Astruc {
    fn map_function(index: usize) -> usize {
        2 * index
    }
    fn map_attempt(&self) {
        (0..10).map(Self::map_function)
            .for_each(|i| println!("{i}"));
    }
}
Run Code Online (Sandbox Code Playgroud)