collect
2022/2/26 15:50:00
イテレータを消費し、結果の値をコレクションデータ型に集結させるメソッド
イテレータを消費し、結果の値をコレクションデータ型に集結させるメソッド
let v1 = vec![1, 2, 3];
let v2:Vec<u32> = v1.iter().map(|x|{x + 1}).collect();
assert_eq!(v1, vec![1, 2, 3]);
assert_eq!(v2, vec![2, 3, 4]);
let v1:Vec<String> = vec![String::from("Hoge"), String::from("Fuga"), String::from("Foo")];
let v2:Vec<String> = v1.iter().map(|x|{format!("{}{}", x, x)}).collect();
assert_eq!(v1, vec![String::from("Hoge"), String::from("Fuga"), String::from("Foo")]);
assert_eq!(v2, vec![String::from("HogeHoge"), String::from("FugaFuga"), String::from("FooFoo")]);
let v1:Vec<String> = vec![String::from("Hoge"), String::from("Fuga"), String::from("Foo")];
//所有権の移動が発生し、v1が使えなくなる
let v2:Vec<String> = v1.into_iter().filter(|x|{x.len() == 3}).collect();
assert_eq!(v1, vec![String::from("Hoge"), String::from("Fuga"), String::from("Foo")]);
assert_eq!(v2, vec![String::from("Foo")]);
let v1:Vec<String> = vec![String::from("Hoge"), String::from("Fuga"), String::from("Foo")];
let v2:Vec<&String> = v1.iter().filter(|x|{x.len() == 3}).collect();
assert_eq!(v1, vec![String::from("Hoge"), String::from("Fuga"), String::from("Foo")]);
assert_eq!(v2, vec![&String::from("Foo")]);
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
println!("{:?}", args);
}