美文网首页RUST编程
Rust 编程视频教程(进阶)——026_4 高级 trait4

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

作者: 令狐壹冲 | 来源:发表于2020-03-10 09:25 被阅读0次

视频地址

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

源码地址

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

讲解内容

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<T> 上实现 Display,而孤儿规则阻止我们直接这么做,因为 Display trait 和 Vec<T> 都定义于我们的 crate 之外。我们可以创建一个包含 Vec<T> 实例的 Wrapper 结构体,然后再实现。

相关文章

网友评论

    本文标题:Rust 编程视频教程(进阶)——026_4 高级 trait4

    本文链接:https://www.haomeiwen.com/subject/xtpidhtx.html