更安全的版本。这个跳过失败的解析,这样失败的展开就不会恐慌。
使用read_line 读取单行。
let mut buf = String::new();
// use read_line for reading single line
std::io::stdin().read_to_string(&mut buf).expect("");
// this one skips failed parses so that failed unwrap doesn't panic
let v: Vec<i32> = buf
.split_whitespace() // split string into words by whitespace
.filter_map(|w| w.parse().ok()) // calling ok() turns Result to Option so that filter_map can discard None values
.collect(); // collect items into Vector. This determined by type annotation.
您甚至可以像这样阅读 Vector of Vectors。
let stdin = io::stdin();
let locked = stdin.lock();
let vv: Vec<Vec<i32>> = locked.lines()
.filter_map(
|l| l.ok().map(
|s| s.split_whitespace()
.filter_map(|word| word.parse().ok())
.collect()))
.collect();
以上一个适用于像这样的输入
2 424 -42 124
42 242 23 22 241
24 12 3 232 445
然后把它们变成
[[2, 424, -42, 124],
[42, 242, 23, 22, 241],
[24, 12, 3, 232, 445]]
filter_map 接受一个返回 Option<T> 并过滤掉所有 Nones 的闭包。
ok() 将Result<R,E> 变为Option<R>,以便在这种情况下过滤错误。