Rust Deref trait:智能指针的解引用魔法
学习Deref trait如何让智能指针像普通引用一样使用,以及自动解引用规则 · 难度:入门 · +15XP
Deref trait的作用
Deref trait允许重载解引用运算符*,使得智能指针(如Box、Rc)可以像普通引用一样被解引用。Rust还会自动插入解引用操作,称为“自动解引用”(deref coercion),让代码更简洁。
实现Deref
任何实现了Deref的类型都可以使用*操作符。例如自定义一个智能指针:
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
let m = MyBox(5);
assert_eq!(5, *m); // 解引用
自动解引用规则
当函数参数期望引用时,Rust会自动将智能指针解引用。例如:
fn hello(name: &str) {
println!("Hello, {}!", name);
}
let m = MyBox(String::from("Rust"));
hello(&m); // 自动 &MyBox -> &String -> &str| 类型 | 实现Deref | 自动解引用目标 |
|---|---|---|
| &T | 是 | T |
| Box<T> | 是 | T |
| Rc<T> | 是 | T |
| String | 是 | &str |
练习提示
自定义一个EvenNumber类型,只允许存储偶数,并实现Deref使得可以解引用为i32。注意DerefMut也可用于可变解引用。