視頻地址
頭條地址:https://www.ixigua.com/i6775861706447913485
B站地址:https://www.bilibili.com/video/av81202308/
源碼地址
github地址:https://github.com/anonymousGiga/learn_rust
講解內(nèi)容
1、父 trait 用于在另一個(gè) trait 中使用某 trait 的功能
有時(shí)我們可能會(huì)需要某個(gè) trait 使用另一個(gè) trait 的功能。在這種情況下,需要能夠依賴相關(guān)的 trait 也被實(shí)現(xiàn)。這個(gè)所需的 trait 是我們實(shí)現(xiàn)的 trait 的 父(超) trait(supertrait)。
(1)錯(cuò)誤例子:
use std::fmt;
trait OutPrint: fmt::Display { //要求實(shí)現(xiàn)DisPlay trait
fn out_print(&self) {
let output = self.to_string();
println!("output: {}", output);
}
}
struct Point {
x: i32,
y: i32,
}
impl OutPrint for Point {}
fn main() {
println!("Hello, world!");
}
(2)正確例子:
use std::fmt;
trait OutPrint: fmt::Display {
fn out_print(&self) {
let output = self.to_string();
println!("output: {}", output);
}
}
struct Point {
x: i32,
y: i32,
}
impl OutPrint for Point {}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn main() {
println!("Hello, world!");
}
2、newtype 模式用以在外部類(lèi)型上實(shí)現(xiàn)外部 trait
孤兒規(guī)則(orphan rule):只要 trait 或類(lèi)型對(duì)于當(dāng)前 crate 是本地的話就可以在此類(lèi)型上實(shí)現(xiàn)該 trait。一個(gè)繞開(kāi)這個(gè)限制的方法是使用 newtype 模式(newtype pattern)。
例子:
use std::fmt;
struct Wrapper(Vec<String>);
impl fmt::Display for Wrapper {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}]", self.0.join(", "))
}
}
fn main() {
let w = Wrapper(vec![String::from("hello"),
String::from("world")]);
println!("w = {}", w);
}
說(shuō)明:
在上述例子中,我們?cè)?Vec<T> 上實(shí)現(xiàn) Display,而孤兒規(guī)則阻止我們直接這么做,因?yàn)?Display trait 和 Vec<T> 都定義于我們的 crate 之外。我們可以創(chuàng)建一個(gè)包含 Vec<T> 實(shí)例的 Wrapper 結(jié)構(gòu)體,然后再實(shí)現(xiàn)。