rust 学习 解引用

rust 复制代码
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> MyBox<T> {
    fn new(x:T) -> MyBox<T> {
        MyBox(x)
    }
}

impl<T> Deref for MyBox<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.0
    }
}

fn hello(name:&str) {
    println!("Hello,{}",name)
}
fn main() {
	let x = 5;
	let y =MyBox::new(x);
	assert_eq!(5,x);
	assert_eq!(5,*y);
	
	let m = MyBox::new(String::from("Rust"));
	hello(&m);  
//虽然m是Mybox对象,但是自动解引用   Box<String> -> String -> &str 的隐式转换,只要链条上的类型实现了 Deref 特征。
	hello("wzg");
}