Primitive variable does not live long enough

前端 未结 1 1812
-上瘾入骨i
-上瘾入骨i 2021-01-20 21:19

There is an error in this piece of code:

let a: Vec<_> = (1..10).flat_map(|x| (1..x).map(|_| x)).collect();

The error message:

<
相关标签:
1条回答
  • 2021-01-20 22:12

    This does not work because you capture x by reference when you do map(|_| x). x is not a variable local to the closure, so it is borrowed. To not borrow x, you must use the move keyword:

    let a: Vec<_> = (1..10).flat_map(|x| (1..x).map(move |_| x)).collect();
    

    But this is more idiomatic to write (for the same output):

    use std::iter::repeat;
    let b: Vec<_> = (2..10).flat_map(|x| repeat(x).take(x - 1)).collect();
    

    Concerning the "why" question: some people could want to borrow a copyable data, so the capturing rules are the same:

    • Default: by reference,
    • With the move keyword: take the ownership.
    0 讨论(0)
提交回复
热议问题