在 Rust 中从数组调用闭包

2024-03-27

如何迭代一系列闭包,依次调用每个闭包?

通过函数,我发现我可以通过迭代数组并取消引用生成的值来做到这一点:

fn square(x: int) -> int { x * x }

fn add_one(x: int) -> int { x + 1 }

fn main() {
    let funcs  = [square, add_one];
    for func in funcs.iter() {
        println!("{}", (*func)(5i));
    }
}

但是,当我尝试对闭包执行相同操作时,出现错误:

fn main() {
    let closures = [|x: int| x * x, |x| x + 1];
    for closure in closures.iter() {
        println!("{}", (*closure)(10i));
    }
}

生产:

<anon>:4:24: 4:34 error: closure invocation in a `&` reference
<anon>:4         println!("{}", (*closure)(10i));
                                ^~~~~~~~~~
note: in expansion of format_args!
<std macros>:2:23: 2:77 note: expansion site
<std macros>:1:1: 3:2 note: in expansion of println!
<anon>:4:9: 4:41 note: expansion site
<anon>:4:24: 4:34 note: closures behind references must be called via `&mut`
<anon>:4         println!("{}", (*closure)(10i));
                                ^~~~~~~~~~
note: in expansion of format_args!
<std macros>:2:23: 2:77 note: expansion site
<std macros>:1:1: 3:2 note: in expansion of println!
<anon>:4:9: 4:41 note: expansion site

如果我尝试声明迭代变量ref mut,它仍然不起作用:

fn main() {
    let closures = [|x: int| x * x, |x| x + 1];
    for ref mut closure in closures.iter() {
        println!("{}", (*closure)(10i));
    }
}

结果是:

<anon>:4:24: 4:39 error: expected function, found `&|int| -> int`
<anon>:4         println!("{}", (*closure)(10i));
                                ^~~~~~~~~~~~~~~
note: in expansion of format_args!
<std macros>:2:23: 2:77 note: expansion site
<std macros>:1:1: 3:2 note: in expansion of println!
<anon>:4:9: 4:41 note: expansion site

如果我添加另一个取消引用:

fn main() {
    let closures = [|x: int| x * x, |x| x + 1];
    for ref mut closure in closures.iter() {
        println!("{}", (**closure)(10i));
    }
}

我回到原来的错误:

<anon>:4:24: 4:35 error: closure invocation in a `&` reference
<anon>:4         println!("{}", (**closure)(10i));
                                ^~~~~~~~~~~
note: in expansion of format_args!
<std macros>:2:23: 2:77 note: expansion site
<std macros>:1:1: 3:2 note: in expansion of println!
<anon>:4:9: 4:42 note: expansion site
<anon>:4:24: 4:35 note: closures behind references must be called via `&mut`
<anon>:4         println!("{}", (**closure)(10i));
                                ^~~~~~~~~~~
note: in expansion of format_args!
<std macros>:2:23: 2:77 note: expansion site
<std macros>:1:1: 3:2 note: in expansion of println!
<anon>:4:9: 4:42 note: expansion site

我在这里缺少什么?是否有文档描述其工作原理?


The .iter()向量的方法产生不可变的引用,你需要可变的引用来调用闭包,因此你应该使用.iter_mut() :

fn main() {
    let mut closures = [|x: int| x * x, |x| x + 1];
    for closure in closures.iter_mut() {
        println!("{}", (*closure)(10i));
    }
}

-----

100
11
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Rust 中从数组调用闭包 的相关文章

随机推荐