trait
在 rust
中无处不在,所以学会熟练使用是必须的,在此做个笔记。
- 在实现
trait
是必须实现所有方法(带默认实现的除外)
trait 默认实现
pub trait Summary {
fn summarize(&self) -> String;
// 带默认实现的函数
fn line(&self) {
println!("--------------------------");
}
}
trait 作为参数
pub trait Summary {
fn summarize(&self) -> String;
fn line(&self);
}
struct Point {
x: f64,
y: f64,
}
impl Point {
fn print(&self) {
println!("x: {}, y: {}", self.x, self.x);
}
fn info(p: &Point) {
println!("x: {}, y: {}", p.x, p.x);
}
}
impl Summary for Point {
fn summarize(&self) -> String {
format!("----- Point Object Summary -----\nx: {0}, y: {1}", self.x, self.y)
}
fn line(&self) {
println!("-------------------------------");
}
}
// Trait 作为参数
fn notify(item: &impl Summary) {
item.line();
println!("{}", item.summarize());
// item.print() 不能调用类型的方法
}
fn main() {
let p1 = Point {x: 10.2, y: 23.8};
notify(&p1);
}
trait
作为函数参数是只能调用 trait 自身的方法,不能调用具体类型的方法,如上面不能调用 item.print()
。
Trait Bound 语法
// Trait 作为参数
fn notify(item: &impl Summary) {
item.line();
println!("{}", item.summarize());
}
// ## Trait Bound 语法, 泛型写法
fn notify<T: Summary>(item: &T) {
item.line();
println!("{}", item.summarize());
}
where
简化 Trait Bound 语法
有时候参数要使用比较多的 trait
,这时Trait Bound
语法就会显得笔记乱,这时可以使用 where
来进行简化。
fn notify<T>(item: &T)
where
T: Summary + Display,
{
item.line();
println!("{}", item.summarize());
println!("{}", item);
}
简化后 T
代表哪些 Trait
就挪到 where
后面了。这样就让<>
里边的内容显得比较干净。