视频地址
头条地址:https://www.ixigua.com/i6775861706447913485
B站地址:https://www.bilibili.com/video/av81202308/
源码地址
github地址:https://github.com/anonymousGiga/learn_rust
讲解内容
自定义智能指针MyBox:实现Deref trait
//+++++++错误代码+++++++++++++++++
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> MyBox<T> {
MyBox(x)
}
}
fn main() {
let x = 5;
let y = MyBox::new(x);
assert_eq!(5, x);
assert_eq!(5, *y);
}
//+++++++++正确代码++++++++++++++++
//实现Deref Trait
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> { //为MyBox实现Deref trait
type Target = T;
fn deref(&self) -> &T { //注意:此处返回值是引用,因为一般并不希望解引用获取MyBox<T>内部值的所有权
&self.0
}
}
fn main() {
let x = 5;
let y = MyBox::new(x);
assert_eq!(5, x);
assert_eq!(5, *y); //实现Deref trait后即可解引用,使用*y实际等价于 *(y.deref())
}
网友评论