rust中的map,iter,filter,collect,sum不仅神奇,功能强大且灵活,下面为大家介绍灵活的几种形式。
fn main(){
let vec = vec![1, 2, 3, 4, 5];
let vecstr:Vec<_> = vec.iter().map(|z|z.to_string()).collect();
//let vecstr = vec.iter().map(|z|z.to_string()).collect::<Vec<_>>();
//let vecstr:Vec<String> = vec.iter().map(|x|x.to_string()).collect();
println!("新的Vec是:{:?}",vecstr);
let vec = vec![1, 2, 3, 4, 5];
//let sum = vec.iter().sum::();
let sum:i32 = vec.iter().sum();
println!("总和为:{}", sum);
for num in (0..=9).filter(|x| x % 3 == 0) {
eprint!("{},", num);
}
}
let str =vec!["yes","ok","greet"];
//let mystr = str.iter().filter(|x|x.contains("e")).collect::<Vec<_>>();
let mystr:Vec<_> = str.iter().filter(|x|x.contains("e")).collect();
println!("筛选出的str:{:?}", mystr);
/*输出如下内容
新的Vec是:["1", "2", "3", "4", "5"]
总和为:15
0,3,6,9,筛选出的str:["yes", "greet"]
*/