0
点赞
收藏
分享

微信扫一扫

Rust 编程视频教程(进阶)——011_2 自定义 Box


视频地址

头条地址: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())
}


举报

相关推荐

0 条评论