原始变量的寿命不够长 [英] Primitive variable does not live long enough

查看:124
本文介绍了原始变量的寿命不够长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码有错误:

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

错误消息:

error[E0597]: `x` does not live long enough
 --> src/main.rs:2:57
  |
2 |     let a: Vec<_> = (1..10).flat_map(|x| (1..x).map(|_| x)).collect();
  |                                                     --- ^-          - borrowed value needs to live until here
  |                                                     |   ||
  |                                                     |   |borrowed value only lives until here
  |                                                     |   borrowed value does not live long enough
  |                                                     capture occurs here

但为什么?

是原始类型,即它应该被克隆。

Is is a primitive type, i.e. it should be cloned anyway.

我理解错误了什么?

推荐答案

这不起作用,因为当你执行 map(| _ | x)时你通过引用捕获 x code>。 x 不是闭包的本地变量,因此它是借用的。要不借用 x ,您必须使用 move 关键字:

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.

这篇关于原始变量的寿命不够长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆