Moc*_*han 2 dictionary flat rust
我正在尝试编写一个带有字符串索引和字符串中每个字符的向量.
在下面的示例中,0 J,0 a,0 n ... 1 J,1i,...
fn main() {
let names = vec!["Jane", "Jill", "Jack", "Johne"];
let name3 = names.iter().enumerate().flat_map(|(i, name)| {
let letters = name.chars();
let mut is = Vec::new();
for _k in 0..name.len() {
is.push(i);
}
is.iter().zip(letters).collect::<Vec<_>>()
});
for i in name3 {
println!("{:?}", i);
}
}
Run Code Online (Sandbox Code Playgroud)
这给了我错误
error[E0597]: `is` does not live long enough
--> src/main.rs:9:9
|
9 | is.iter().zip(letters).collect::<Vec<_>>()
| ^^ borrowed value does not live long enough
10 | });
| - `is` dropped here while still borrowed
...
14 | }
| - borrowed value needs to live until here
Run Code Online (Sandbox Code Playgroud)
我不明白这里发生了什么.我已经收集了is价值.
古怪的是,如果我不停地翻转letters和is,它的工作原理.
letters.zip(is)
Run Code Online (Sandbox Code Playgroud)
调用is.iter()返回对内部值的引用is.您的最终迭代器类型正在尝试返回这些引用,除了Vec保留值已被释放.
最简单的解决方法是切换到into_iter,取得Vec其所有值的所有权.更有效的解决方法是避免创建一个Vec:
fn main() {
let names = vec!["Jane", "Jill", "Jack", "Johne"];
let name3 = names
.iter()
.enumerate()
.flat_map(|(i, name)| name.chars().map(move |c| (i, c)));
for i in name3 {
println!("{:?}", i);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我不停地翻转
letters和is,它的工作原理.
是的,zip采用实现的值IntoIterator.通过翻转参数,你最终隐含地调用into_iter了Vec.如果你这样做,你会得到同样不受欢迎的行为letters.zip(&is).