Rust 編程視頻教程(進階)——026

視頻地址

頭條地址:https://www.ixigua.com/i6775861706447913485

源碼地址

github地址:見擴展鏈接。

講解內容

1、父 trait 用於在另一個 trait 中使用某 trait 的功能有時我們可能會需要某個 trait 使用另一個 trait 的功能。在這種情況下,需要能夠依賴相關的 trait 也被實現。這個所需的 trait 是我們實現的 trait 的 父(超) trait(supertrait)。(1)錯誤例子:

<code>use std::fmt;
trait OutPrint: fmt::Display { //要求實現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!");
}/<code>

(2)正確例子:

<code>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!");
}/<code>

2、newtype 模式用以在外部類型上實現外部 trait孤兒規則(orphan rule):只要 trait 或類型對於當前 crate 是本地的話就可以在此類型上實現該 trait。一個繞開這個限制的方法是使用 newtype 模式(newtype pattern)。例子:

<code>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);
}/<string>/<code>

說明:在上述例子中,我們在 Vec 上實現 Display,而孤兒規則阻止我們直接這麼做,因為 Display trait 和 Vec 都定義於我們的 crate 之外。我們可以創建一個包含 Vec 實例的 Wrapper 結構體,然後再實現。


分享到:


相關文章: