《Rust 编程第一课》 学习笔记 day25

107 阅读1分钟

大家好,我是砸锅。一个摸鱼八年的后端开发。熟悉 Go、Lua。第二十五天还是继续和大家一起学习 Rust😊

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 9 天,点击查看活动详情

类型转换相关 trait: From / Into / AsRef / AsMut

值类型到值类型的转换:From / Into / TryFrom / TryInto

引用类型到引用类型的转换:AsRef / AsMut

From / Into

pub trait From<T> {
	fn from(T) -> Self;
}

pub trait Into<T> {
	fn into(self) -> T;
}

// 实现 From 会自动实现 Into
impl<T, U> Into<U> for T where U: From<T> {
	fn into(self) -> U {
		U::from(self)
	}
}

AsRef / AsMut

pub trait AsRef<T> where T: ?Sized {
    fn as_ref(&self) -> &T;
}

pub trait AsMut<T> where T: ?Sized {
    fn as_mut(&mut self) -> &mut T;
}

操作符相关 Trait:Deref / DerefMut

pub trait Deref {
    // 解引用出来的结果类型
    type Target: ?Sized;
    fn deref(&self) -> &Self::Target;
}

pub trait DerefMut: Deref {
    fn deref_mut(&mut self) -> &mut Self::Target;
}

Debug / Display / Default

pub trait Debug {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>;
}

pub trait Display {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>;
}

Debug 用 {:?} 来打印,Display 用 {} 打印

Default

pub trait Default {
    fn default() -> Self;
}

Default trait 为类型提供了缺省值

image.png

智能指针

智能指针一定是胖指针,而胖指针不一定是一个智能指针,例如智能指针 String 和 &str 的区别:

image.png

String 除了多了一个 capacity 字段,还拥有堆上的值所有权,而 &str 没有所有权,这是 Rust 中智能指针和普通胖指针的区别

在 Rust 里,凡是需要做资源回收的数据结构,且实现了 Deref / DerefMut / Drop ,都是智能指针

此文章为2月Day4学习笔记,内容来源于极客时间《Rust 编程第一课》