Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

:timing
:sccache 1

Tips and Traps

  1. Range does has the map method.

  2. When constructing a range using m..n, an empty range is yield if mnm \ge n. If you need a decreasing range, first construst an increasing range and then call the reverse method on it.

  3. Module std::collections has a good summary on when to each which collection in Rust.

0..5
0..5
for i in 0..5 {
    println!("{}", i);
}
0
1
2
3
4
()
(0..5).for_each(|i|
    println!("{}", i)
)
0
1
2
3
4
()
for i in (0..5).step_by(2) {
    println!("{}", i);
}
0
2
4
()
for i in (0..5).rev() {
    println!("{}", i);
}
4
3
2
1
0
()
for i in (0..5).rev().step_by(2) {
    println!("{}", i);
}
4
2
0
()
(1..10).map(|x| x + 1).collect::<Vec<_>>()
[2, 3, 4, 5, 6, 7, 8, 9, 10]
(1..10).filter(|x| x % 3 == 0).collect::<Vec<_>>()
[3, 6, 9]
(1..10).filter(|x| x % 3 == 0).next()
Some(3)
let x = (1..10).filter(|x| x % 3 == 0).next().unwrap();
x
3
(1..10).filter(|x| x % 2 == 0).count()
4
(1..10).max()
Some(9)
(1..10).iter().sum()
(1..10).iter().sum()
        ^^^^ method not found in `std::ops::Range<{integer}>`
no method named `iter` found for struct `std::ops::Range<{integer}>` in the current scope
let v = vec![1, 2, 3];
v
[1, 2, 3]
let s: i32 = v.iter().sum();
s
6
v.iter().sum::<i32>()
6
(v.iter().sum::<i32>() as f64) / 6.0
1.0
v.iter().sum::<i32>() as f64 / 6.0
1.0