【发布时间】:2022-01-13 06:56:28
【问题描述】:
结果
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]。
为什么我会得到这个结果?
【问题讨论】:
结果
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]。
为什么我会得到这个结果?
【问题讨论】:
这与flat_map 无关,但与std::ops::Range 无关,std::ops::Range 被定义为“包含在下面,只在上面”。也就是说,在1..4-范围内,最大值将是 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]
)
}
【讨论】: