【发布时间】:2018-12-03 19:13:56
【问题描述】:
我有一个字符串迭代器lines,它是从标准输入获得的
use std::io::{self, BufRead};
let mut stdin = io::stdin();
let lines = stdin.lock().lines().map(|l| l.unwrap());
lines 迭代器产生String 类型的值,而不是&str。我想创建一个迭代输入单词而不是行的迭代器。看起来这应该是可行的,但我天真的尝试不起作用:
let words = lines.flat_map(|l| l.split_whitespace());
编译器告诉我,l 在被借用的同时被删除了,这是有道理的:
error[E0597]: `l` does not live long enough
--> src/lib.rs:6:36
|
6 | let words = lines.flat_map(|l| l.split_whitespace());
| ^ - `l` dropped here while still borrowed
| |
| borrowed value does not live long enough
7 | }
| - borrowed value needs to live until here
还有其他干净的方法可以做到这一点吗?
【问题讨论】:
标签: rust iterator borrow-checker