Iterator `map` and `filter`

  • map 要素は参照として渡される
  • filte 要素はダブル参照として渡される

map

例: Vec<bool>

// map<B, F>(self, f: F) -> Map<Self, F> where F: FnMut(Self::Item) -> B, // Self::Item = &T
let nums = [1, 2, 3, 4, 5];
let is_evens = nums.iter().map(|&n| {
    if n % 2 == 0 {
        true
    } else {
        false
    }
}).collect::<Vec<bool>>();

例: Vec<String>

fn hello(names: &Vec<String>) -> Vec<String> {
    names.iter().map(|x| "hello ".to_string() + x).collect()
}

let names = vec!["tanaka".to_string(), "yoshida".to_string(), "ito".to_string()];
// 要素の所有権は移らない
let result = hello(&names);

NOTE: map定義

fn map<B, F>(self, f: F) -> Map<Self, F>
where
    F: FnMut(Self::Item) -> B, 

filter

fn even<'a>(arr: &'a Vec<i32>) -> Vec<&'a i32> {
    arr.iter().filter(|&x| *x % 2 == 0).collect()
}

let arr = vec![1,2,3,4,5];
let ret = even(&arr);

NOTE: filter定義

fn filter<P>(self, predicate: P) -> Filter<Self, P>
where
    P: FnMut(&Self::Item) -> bool, 

NOTE: cloned メソッドによって要素の中身をすべてコピーされる

fn copy_even(arr: &Vec<i32>) -> Vec<i32> {
    arr.iter().filter(|&x| *x % 2 == 0).cloned().collect()
}

let arr = vec![1,2,3,4,5];
let arr = copy_even(&arr);