理解Rust的引用與借用(好文鏈接)
#![feature(core_intrinsics)] fn print_type_of<T>(_: T) { println!("{}", unsafe { std::intrinsics::type_name::<T>() }); } fn main() { let ref a: i32; a = &1; let ref a: i32 = 1; print_type_of(a); let c: &u32 = &&&&&2; print_type_of(c); }
上面2個a的類型都是&i32
enum帶參數時使用match會move走enum的參數,如下這樣寫會報錯
#![feature(core_intrinsics)] fn print_type_of<T>(_: T) { println!("{}", unsafe { std::intrinsics::type_name::<T>() }); } fn main() { let os = Some(String::from("s")); match os { Some(s) => { print_type_of(s); }, _ => () }; println!("{:?}", os); }
改下match的參數匹配模式,用ref來匹配就不會出錯了
#![feature(core_intrinsics)] fn print_type_of<T>(_: T) { println!("{}", unsafe { std::intrinsics::type_name::<T>() }); } fn main() { let os = Some(String::from("s")); match os { Some(ref s) => { print_type_of(s); // s此時是&alloc::string::String類型 }, _ => () }; println!("{:?}", os); }
如果match的對象是一個引用,會發現參數是引用類型,比如
#![feature(core_intrinsics)] fn print_type_of<T>(_: T) { println!("{}", unsafe { std::intrinsics::type_name::<T>() }); } fn main() { let os = &Some(String::from("s")); match os { Some(s) => { print_type_of(s); }, _ => () }; }
打印的是&alloc::string::String
其實和下面的代碼一樣
#![feature(core_intrinsics)] fn print_type_of<T>(_: T) { println!("{}", unsafe { std::intrinsics::type_name::<T>() }); } fn main() { let os = &Some(String::from("s")); match os { &Some(ref s) => { print_type_of(s); }, _ => () }; }