父类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)
}