Primitive variable does not live long enough

谁说我不能喝 提交于 2019-12-01 21:01:35

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!