January 2019
Beginner to intermediate
554 pages
13h 31m
English
Using the map method is simple:
// using_map.rsfn get_nth(items: &Vec<usize>, nth: usize) -> Option<usize> { if nth < items.len() { Some(items[nth]) } else { None }}fn double(val: usize) -> usize { val * val}fn main() { let items = vec![7, 6, 4, 3, 5, 3, 10, 3, 2, 4]; println!("{}", items.len()); let doubled = get_nth(&items, 4).map(double); println!("{:?}", doubled);}
In the preceding code, we have a method called get_nth that gives us the nth element from Vec<usize> and returns None if it couldn't find one. We then have a use case where we want to double the value. We can use the map method on the return value of get_nth, passing in the double function we defined previously. Alternatively, we could have provided a closure ...
Read now
Unlock full access