rust trait 的一些遗漏点(五)

父类trait 和 子类trait 如果都实现了同一个方法a,怎么分别调用

trait ParentTrait {
    fn a(&self) {
        println!("Called ParentTrait's a");
    }
}

trait ChildTrait: ParentTrait {
    fn a(&self) {
        println!("Called ChildTrait's a");
    }
}

struct Example;

impl ParentTrait for Example {}

impl ChildTrait for Example {
    fn a(&self) {
        println!("ChildTrait implementation for Example");
    }
}


fn main() {
    let example = Example;

    // 调用 ChildTrait 实现的方法
    ChildTrait::a(&example);

    // 显式地调用 ParentTrait 的方法
    <Example as ParentTrait>::a(&example);
}


实现子类另外案例

use std::fmt;

// 定义一个 Clone 特性
pub trait Clone {
    fn clone(&self) -> Self;
}

// 定义一个 Drawable 特性,要求实现 Clone 特性
pub trait Drawable: Clone {
    fn draw(&self);
}

// 为 Position 结构体实现 Clone 特性
#[derive(Copy)]
pub struct Position {
    pub x: usize,
    pub y: usize,
}

// 为 Position 结构体实现 Clone 特性
impl Clone for Position {
    fn clone(&self) -> Self {
        *self
    }
}

// 为 Position 结构体实现 Drawable 特性
impl Drawable for Position {
    fn draw(&self) {
        println!("Drawing at position: ({}, {})", self.x, self.y);
    }
}

fn main() {
    let pos1 = Position { x: 10, y: 20 };
    pos1.draw(); // 调用 draw 方法

    let pos2 = pos1.clone(); // 调用 clone 方法
    println!("Cloned position: ({}, {})", pos2.x, pos2.y);

    // 使用泛型函数处理实现了 Drawable 和 Clone 特性的类型
    draw_and_clone(&pos1);
}

// 泛型函数,要求 T 实现 Drawable 和 Clone 特性
fn draw_and_clone<T: Drawable + Clone>(item: &T) {
    item.draw();
    let cloned_item = item.clone();
    println!("Cloned item drawn: ({}, {})", cloned_item.x, cloned_item.y);
}

自定义trait 拓展方法实现了 系统的类型,可以通过 use trait 来为系统方法拓展类型,例如这里 拓展了方法 LogError,然后Result 类型可以调用 LogError ,但是需要导入use log_error_ext::LogError; 该trait 才行

use std::error::Error;
use log_error_ext::LogError;

// 定义模块
mod log_error_ext {
    use std::error::Error;

    // 定义一个 trait,用于扩展 `Result` 类型的方法
    pub trait LogError<T, E> {
        fn log_error(self) -> Result<T, E>;
    }

    // 为 `Result` 类型实现 `LogError` trait
    impl<T, E: Error> LogError<T, E> for Result<T, E> {
        fn log_error(self) -> Result<T, E> {
            match &self {
                Err(e) => eprintln!("Error occurred: {}", e),
                _ => {}
            }
            self
        }
    }
}


fn read_file_v2(path: &str) -> Result<String, Box<dyn Error>> {
    // 使用自定义的 `log_error` 方法记录错误信息
    let mut file = File::open(path).log_error()?;
    let mut contents = String::new();
    file.read_to_string(&mut contents).log_error()?;
    Ok(contents)
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gitxuzan_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值