Ben Chuanlong Du's Blog

It is never too late to learn.

Range in Rust

In [ ]:
: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 $m \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.

In [26]:
0..5
Out[26]:
0..5
In [29]:
for i in 0..5 {
    println!("{}", i);
}
0
1
2
3
4
Out[29]:
()
In [5]:
(0..5).for_each(|i|
    println!("{}", i)
)
0
1
2
3
4
Out[5]:
()
In [31]:
for i in (0..5).step_by(2) {
    println!("{}", i);
}
0
2
4
Out[31]:
()
In [34]:
for i in (0..5).rev() {
    println!("{}", i);
}
4
3
2
1
0
Out[34]:
()
In [35]:
for i in (0..5).rev().step_by(2) {
    println!("{}", i);
}
4
2
0
Out[35]:
()
In [41]:
(1..10).map(|x| x + 1).collect::<Vec<_>>()
Out[41]:
[2, 3, 4, 5, 6, 7, 8, 9, 10]
In [42]:
(1..10).filter(|x| x % 3 == 0).collect::<Vec<_>>()
Out[42]:
[3, 6, 9]
In [43]:
(1..10).filter(|x| x % 3 == 0).next()
Out[43]:
Some(3)
In [45]:
let x = (1..10).filter(|x| x % 3 == 0).next().unwrap();
x
Out[45]:
3
In [55]:
(1..10).filter(|x| x % 2 == 0).count()
Out[55]:
4
In [56]:
(1..10).max()
Out[56]:
Some(9)
In [58]:
(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
In [59]:
let v = vec![1, 2, 3];
v
Out[59]:
[1, 2, 3]
In [61]:
let s: i32 = v.iter().sum();
s
Out[61]:
6
In [69]:
v.iter().sum::<i32>()
Out[69]:
6
In [73]:
(v.iter().sum::<i32>() as f64) / 6.0
Out[73]:
1.0
In [74]:
v.iter().sum::<i32>() as f64 / 6.0
Out[74]:
1.0

Comments