fn main() {
// 对于Copy类型
// 三种等效写法
// 1. map(|x| *x)
// 2. map(|&x| x)
// 3. copied(), 优先使用,结构清晰可读性高,一看就知道发生了复制
// 这三种写法,都是在复制元素,如果是非Copy类型将发生所有权转移
let arr1 = [1, 2, 3, 4, 5];
let vec1: Vec<i32> = arr1.iter().map(|x| *x + 1).collect();
let vec2: Vec<i32> = arr1.iter().map(|&x| x * 2).collect();
let vec3: Vec<i32> = arr1.iter().copied().filter(|x| x & 1 == 1).collect();
println!("vec1 = {:?}", vec1);
println!("vec2 = {:?}", vec2);
println!("vec3 = {:?}", vec3);
// String不是copy类型
let string_arr = ["a".to_string(), "b".to_string(), "c".to_string()];
// 编译不通过
// let vec4: Vec<String> = str_arr.iter().copied().collect();
// cannot move out of `*x` which is behind a shared reference
// move occurs because `*x` has type `String`, which does not implement the `Copy` trait
// let vec4: Vec<String> = str_arr.iter().map(|x| *x).collect();
// move occurs because `x` has type `String`, which does not implement the `Copy`
// let vec4: Vec<String> = str_arr.iter().map(|&x| x).collect();
let vec4: Vec<String> = string_arr.iter().cloned().collect();
let vec4: Vec<String> = string_arr.iter().map(|x| x.clone()).collect();
// cloned() 创建了全新的String对象,闭包参数x是局部变量,不是引用,拥有所有权
// cannot return value referencing function parameter `x`
// returns a value referencing data owned by the current function
// let vec5: Vec<&str> = str_arr.iter().cloned().map(|x| x.as_str()).collect();
let str_arr = ["a", "b", "c"];
// 所有不可变引用 &T都实现了 Copytrait,无论 T是什么类型。
let vec5: Vec<&str> = str_arr.iter().map(|&x| x).collect();
}