有没有更好的方法在Rust中重写这个方法



我写了这段代码来解析一个看起来像整数板的字符串。类似这样的东西:

1 2 3 4 5
6 7 8 9 1
3 4 5 2 3
1 2 4 5 1
4 6 2 7 3

代码为:

type Cell = (i32, bool);
struct Board {
cells: Vec<Cell>,
}
impl Board {
/// The input to this method is a string consisting of BOARD_WIDTH x BOARD_HEIGHT grid in a String.
fn new(input: String) -> Board {
let cells: Vec<Cell> = input
.lines()
.map(|s| {
s.split_whitespace()
.map(|c| {
let cell_num: i32 = c.parse().unwrap();
return (cell_num, false);
})
.collect()
})
.collect::<Vec<Vec<Cell>>>()
.into_iter()
.flatten()
.collect();
return Board { cells };
}
}

我是Rust的新手,所以我想知道是否有更好的方法来重写这篇文章。我有一个看起来像这样的第一次迭代:

let cells: Vec<Cell> = input
.lines()
.map(|s| {
s.split_whitespace()
.map(|c| {
let cell_num: i32 = c.parse().unwrap();
return (cell_num, false);
})
})
.collect();

你有什么想法吗?谢谢

let cells: Vec<Cell> = input
.lines()
.flat_map(|s| {
s
.split_whitespace()
.map(|c| {
let cell_num: i32 = c.parse().unwrap();
(cell_num, false)
})
})
.collect();

最新更新