走进 Rust:智能指针
Rust 大约 1085 字普通指针
引用以&
符号为标志并借用了他们所指向的值
智能指针
智能指针通常使用结构体实现。不同于结构体的地方在于智能指针实现了trait
:Deref
和Drop
。
一类数据结构,他们的表现类似指针,但是也拥有额外的元数据和功能。
区别
引用:只借用数据的指针。
智能指针:拥有他们(他们指的是智能指针)指向的数据。
标准库中的智能指针
以下struct
就是智能指针:
String
:字符串Vector<T>
:集合Box<T>
:用于在堆上分配值Rc<T>
:一个引用计数类型,其数据可以有多个所有者Ref<T>
和RefMut<T>
:通过efCell<T>
访问。(RefCell<T>
是一个在运行时而不是在编译时执行借用规则的类型)
元祖结构体
与元组类似的结构体,称为元组结构体(tuple structs
)。
元组结构体有着结构体名称,但没有具体的字段名,只有字段的类型。
struct Color(i32, i32, i32);
struct Point(i32, i32);
struct Test(u8);
fn main() {
let c = Color(0, 255, 100);
let p = Point(10, 20);
let t = Test(10);
}
Box<T>
被定义为包含一个元素的元组结构体。
pub struct Box<
T: ?Sized,
#[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
>(Unique<T>, A);
自定义智能指针:获取第一个元祖的元素&self.0
。
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
}
}
阅读 98 · 发布于 2023-05-02
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
minikube start Unable to determine current user's administrator privileges阅读 473
-
走进 Spring Boot 第二步之 SpringApplicaiton 构造函数阅读 3594
-
Spring Boot NoClassDefFoundError: com/mongodb/connection/DefaultClusterFactory阅读 6030
-
Test.class found in top-level directory (unnamed package not allowed in module)阅读 3837
-
MySQL 之 MyISAM 和 InnoDB 区别阅读 2267
-
软考大纲:系统架构设计师阅读 1094
-
Spring Boot 请求转发和重定向阅读 9868
-
javac 错误: 编码 GBK 的不可映射字符阅读 1241
-
Spring Boot2 关闭 Spring Security 权限验证阅读 13969
-
软考-系统架构设计师:Flynn 分类法阅读 2630