How do I create an array of unboxed functions / closures?

后端 未结 2 1063
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 00:09

Editor\'s note: This question was asked before Rust 1.0 and some of the syntax has changed since then, but the underlying concepts remain. Some answers have b

相关标签:
2条回答
  • 2020-12-21 00:40

    It is possible to collect multiple closures from an iterator into a Vec:

    fn main() {
        let a: Vec<_> = (0..10).map(|i| move || i).collect();
    
        println!("{} {} {}", a[1](), a[5](), a[9]());
    }
    

    The move keyword causes ownership of i to be transferred to the closure.

    See also:

    • How do I collect into an array?
    0 讨论(0)
  • 2020-12-21 00:41

    You need to use move || i.

    move implies that this closure will take i by value rather than by reference. By default, these closures would only take references to i. In your case it is forbidden as the lifetime of i is limited to the body of the loop.

    Also, Rust will complain that your array may not be fully initialized. To avoid it, you can either use a Vec<_>, or use std::mem::uninitialized:

    fn main() {
        let mut a: [_; 10] = unsafe { std::mem::uninitialized() };
        for i in 0..10 {
            a[i] = move || i;
        }
        println!("{} {} {}", a[1](), a[5](), a[9]())
    }
    
    0 讨论(0)
提交回复
热议问题