rust 实用工具手册

Vec -> Vec<&str>


#![allow(unused)]
fn main() {
let a = vec!["string".to_string()];
let b:Vec<&str> = a.iter().map(|s| &**s).collect();
let b:Vec<&str> = a.iter().map(std::ops::Deref::deref).collect();
let b:Vec<&str> = a.iter().map(|s| s as &str).collect();
let b:Vec<&str> = a.iter().map(|s| &s[..]).collect();
let b:Vec<&str> = a.iter().map(|s| { let s: &str = s; s }).collect();
let b:Vec<&str> = a.iter().map(|s| s.as_ref()).collect();
let b:Vec<&str> = a.iter().map(AsRef::as_ref).collect();
let b:Vec<&str> = a.iter().map(String::as_str).collect();
assert_eq(vec!["string"], b);
}

Option::map vs Option::and_then


#![allow(unused)]
fn main() {
/// map      把 Some(T) 映射成 Some(U)
/// and_then 把 Some(T) 映射成 Option(U)
/// 也就是说,and_then 是 map 的超集

pub fn map<U, F>(self, f: F) -> Option<U> 
where 
	F: FnOnce(T) -> U

pub fn and_then<U, F>(self, f: F) -> Option<U> 
where 
	F: FnOnce(T) -> Option<U>, 

// 下述例子使用 and_then 实现 map
fn mapper(s: &str) -> i32 {
	s.parse().unwrap()
}
let v = Some("1");
let v2 = v.map(|s| mapper(s));
let v3 = v.and_then(|s| Some(mapper(s)));
asset_eq!(v2, v3);
}

&String vs &str


#![allow(unused)]
fn main() {
use std::mem::size_of;
size_of::<&String>(); // 8
size_of::<&str>();    // 16
}