初步了解学习Rust中traits-学习笔记
在Rust中 Traits:定义可共享的行为
比较类似其他语言中的 接口
Traits
A trait defines functionality a particular type has and can share with other types.
We can use traits to define shared behavior in an abstract way.
We can use trait bounds to specify that a generic type can be any type that has certain behavior. 译: 特质定义了特定类型具有的功能,并且可以与其他类型共享。我们可以使用特质以抽象的方式定义共享行为。我们可以使用特征边界来指定泛型类型可以是具有特定行为的任何类型。
示例(为自定义的结构体实现特定自带traits)
struct Point<T> { x: T, y: T, } // 为Point实现输入打印的trait impl<T: std::fmt::Display> std::fmt::Display for Point<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "({}, {})", self.x, self.y) } } fn show<T: std::fmt::Display>(a: T) { println!("show: {}", a); } // or // fn show(a: impl std::fmt::Display) fn main() { let point = Point { x: 10, y: 20 }; println!("{}", point); show(point); }
示例(自定义Trait,并为结构体实现)
// 定义Trait pub trait Summary { fn summarize(&self) -> String; } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } // 为NewsArticle实现Summary Trait impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{}, by {} ({})", self.headline, self.author, self.location) } } // 为Tweet实现Summary Trait impl Summary for Tweet { fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) } } fn main() { let article = NewsArticle { headline: String::from("2022年12月25日"), location: String::from("北京"), author: String::from("小樊"), content: String::from("..."), }; println!("{}", article.summarize()); let tweet = Tweet { username: String::from("horse_ebooks"), content: String::from("of course, as you probably already know, people"), reply: false, retweet: false, }; println!("1 new tweet:: {}", tweet.summarize()); }
示例(自动派生原生Trait)
#[derive(Debug, PartialEq, Default)] struct Point { x: i32, y: i32, } fn main() { let p1 = Point { x: 1, y: 2 }; let p2 = Point { x: 1, y: 2 }; // By Debug-Trait, output: Point { x: 1, y: 2 } println!("{:?}", p1); // By PartialEq-Trait, output: true println!("{}", p1 == p2); // By Default-Trait(初始化默认值), output: Point { x: 0, y: 0 } let p3 = Point::default(); println!("{:?}", p3); }