的结果
println!("{:?}", (1..4).flat_map(|x| x*2..x*3).collect::<Vec<usize>>())是[2, 4, 5, 6, 7, 8],而我期望的是[2,3,4,5,6,6,7,8,9,8,9,10,11,12]。
我为什么要得到这个结果?
发布于 2021-12-08 10:09:07
这与flat_map无关,而是与std::ops::Range有关,它被定义为“包含在下面,而在上面。”也就是说,在1..4-range中,最高值是3,而不是4。您要寻找的是std::ops::RangeInclusive,您必须在代码中使用它两次:
fn main() {
// Notice that
assert!(!(1..4).contains(&4));
// but
assert!((1..=4).contains(&4));
assert_eq!(
(1..=4).flat_map(|x| x * 2..=x * 3).collect::<Vec<usize>>(),
vec![2, 3, 4, 5, 6, 6, 7, 8, 9, 8, 9, 10, 11, 12]
)
}https://stackoverflow.com/questions/70273055
复制相似问题