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

视频地址

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值