Rust 编程视频教程(进阶)——026_4 高级 trait4

视频地址

头条地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

源码地址

github地址:https://github.com/anonymousGiga/learn_rus...

讲解内容

1、父 trait 用于在另一个 trait 中使用某 trait 的功能
有时我们可能会需要某个 trait 使用另一个 trait 的功能。在这种情况下,需要能够依赖相关的 trait 也被实现。这个所需的 trait 是我们实现的 trait 的 父(超) trait(supertrait)。
(1)错误例子:

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

(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 模式用以在外部类型上实现外部 trait
孤儿规则(orphan rule):只要 trait 或类型对于当前 crate 是本地的话就可以在此类型上实现该 trait。一个绕开这个限制的方法是使用 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);
}

说明:
在上述例子中,我们在 Vec 上实现 Display,而孤儿规则阻止我们直接这么做,因为 Display trait 和 Vec 都定义于我们的 crate 之外。我们可以创建一个包含 Vec 实例的 Wrapper 结构体,然后再实现。

本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
119
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商