走进 Rust:trait
Rust About 1,823 words注意
trait
类似Java
中的接口interface
。
定义 trait
定义Summary
:
pub trait Summary {
fn summarize(&self) -> String;
}
实现Summary
:impl trait for struct
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
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());
默认实现
默认实现的方法无须再次impl
,与Java 8
中interface
的default
方法一样。
pub trait Summary {
fn summarize(&self) -> String {
String::from("(Read more...)")
}
}
trait 作为参数
面向接口编程。
pub fn notify(item: impl Summary) {
println!("Breaking news! {}", item.summarize());
}
Trait Bound 语法
由上述例子item: impl Summary
转变而来的语法糖。参数为接口时,定义泛型。
pub fn notify<T: Summary>(item1: T, item2: T) {
println!("Breaking news1! {}", item1.summarize());
println!("Breaking news2! {}", item2.summarize());
}
通过 + 指定多个 trait bound
参数为实现了Summary
和Display
的trait
。
pub fn notify(item: impl Summary + Display) {
}
通过+
改写。
pub fn notify<T: Summary + Display>(item: T) {
}
通过 where 简化 trait bound
通过+
指定的多个trait bound
。
fn some_function<T: Display + Clone, U: Clone + Debug>(t: T, u: U) -> i32 {
}
通过where
改写。
fn some_function<T, U>(t: T, u: U) -> i32
where T: Display + Clone,
U: Clone + Debug
{
}
函数返回 trait 类型
Tweet
为实现了Summary
的结构体。
fn returns_summarizable() -> impl Summary {
Tweet {
username: String::from("horse_ebooks"),
content: String::from("of course, as you probably already know, people"),
reply: false,
retweet: false,
}
}
Views: 3,009 · Posted: 2020-07-22
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...