来自 flat_map 的神秘行为
Mysterious behavior from flat_map
的结果
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
, which is defined to be "inclusively below and exclusively above". That is, in a 1..4
-range the highest value will be 3, not 4. What you are looking for is 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]
)
}
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
, which is defined to be "inclusively below and exclusively above". That is, in a 1..4
-range the highest value will be 3, not 4. What you are looking for is 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]
)
}