在rust-by- example上实现map-reduce示例后,我尝试执行相同的操作,但数据存储在另一个文件中。编译器现在告诉我,我的data
变量是有'static
生命的借用的,并且寿命不足。我不确定谁在借用我的“数据”,也不确定如何响应编译器的帮助。
我已经尝试添加所有类型注释,以查看是否在某个地方假设了错误的类型,但这没有帮助。如果data
是&'static str
而不是,则使用相同的代码String
。
use std::{fs, thread};
fn main() {
let data = fs::read_to_string("data.txt").unwrap();
let chunked_data = data.split_whitespace();
let mut children = vec![];
for chunk in chunked_data {
children.push(thread::spawn(move || -> u32 {
chunk.chars().map(|c| c.to_digit(10).unwrap()).sum()
}));
}
let mut sums = vec![];
for child in children {
let sum = child.join().unwrap();
sums.push(sum);
}
let res = sums.iter().sum::<u32>();
println!("{}", res);
}
error[E0597]: `data` does not live long enough
--> src/main.rs:5:24
|
5 | let chunked_data = data.split_whitespace();
| ^^^^-------------------
| |
| borrowed value does not live long enough
| argument requires that `data` is borrowed for `'static`
...
22 | }
| - `data` dropped here while still borrowed
我确信这个问题很容易解决,但是我似乎找不到谁在借我的data
。
该split_whitespace
方法在&str
s上运行,这是由于move
循环中的闭合而引起的问题。一个快速的解决方法是对owner进行操作String
:
for chunk in chunked_data.map(|chunk| chunk.to_owned())
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句