In [ ]:
:timing
:sccache 1
Tips and Traps¶
Range does has the
map
method.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 thereverse
method on it.Module std::collections has a good summary on when to each which collection in Rust.
In [26]:
0..5
Out[26]:
In [29]:
for i in 0..5 {
println!("{}", i);
}
Out[29]:
In [5]:
(0..5).for_each(|i|
println!("{}", i)
)
Out[5]:
In [31]:
for i in (0..5).step_by(2) {
println!("{}", i);
}
Out[31]:
In [34]:
for i in (0..5).rev() {
println!("{}", i);
}
Out[34]:
In [35]:
for i in (0..5).rev().step_by(2) {
println!("{}", i);
}
Out[35]:
In [41]:
(1..10).map(|x| x + 1).collect::<Vec<_>>()
Out[41]:
In [42]:
(1..10).filter(|x| x % 3 == 0).collect::<Vec<_>>()
Out[42]:
In [43]:
(1..10).filter(|x| x % 3 == 0).next()
Out[43]:
In [45]:
let x = (1..10).filter(|x| x % 3 == 0).next().unwrap();
x
Out[45]:
In [55]:
(1..10).filter(|x| x % 2 == 0).count()
Out[55]:
In [56]:
(1..10).max()
Out[56]:
In [58]:
(1..10).iter().sum()
In [59]:
let v = vec![1, 2, 3];
v
Out[59]:
In [61]:
let s: i32 = v.iter().sum();
s
Out[61]:
In [69]:
v.iter().sum::<i32>()
Out[69]:
In [73]:
(v.iter().sum::<i32>() as f64) / 6.0
Out[73]:
In [74]:
v.iter().sum::<i32>() as f64 / 6.0
Out[74]: