0
点赞
收藏
分享

微信扫一扫

【rCore OS 开源操作系统】Rust trait 特性快速上手

trait 特性快速上手

什么是 trait

一些权威资料的描述是这样的:

也就是说trait (特性)类似于其他语言中通常称为interfaces的功能,但存在一些差异。

那学过其他语言,我们知道 interface 是干什么的呢?

就是定义某个类型,有那些属性、方法

所以 trait 也可以这么用:

// 这样定义一个叫做 AppendBar 的特性
trait AppendBar {
    fn append_bar(self) -> Self;
}

实现 trait

然后就是所谓的跟interface不一样之处了——如何把它和类型关联呢?

// 给 String 类型实现这个特性
impl AppendBar for String {
    fn append_bar(self) -> Self {
        self + "Bar"
    }
}

使用 trait

这样以来,之后所有String类型的变量,都可以调用 append_bar 方法:

let s = String::from("Foo");
let s = s.append_bar();

配合范型使用

如果我们无法准确描述所需要的类型,但是我们知道它必须要具备一个或者几个trait,那就可以这么描述这个类型:

fn some_func<T: SomeTrait + OtherTrait>(item: T) -> bool {
    item.some_function() && item.other_function()
}

这样就用范型描述了一个同时满足SomeTraitOtherTrait的类型T

举报

相关推荐

0 条评论