01.特征Trait
<h1>01.特征Trait(协议)</h1>
<h2>1、定义特征、实现特征(协议)</h2>
<pre><code>// 定义协议
pub trait Summary {
fn summarize(&amp;self) -&gt; String;
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
// 为类实现协议
impl Summary for Tweet {
fn summarize(&amp;self) -&gt; String {
format!(&quot;{}: {}&quot;, self.username, self.content)
}
}
fn main() {
let tweet = Tweet {
username: String::from(&quot;horse_ebooks&quot;),
content: String::from(&quot;of course, as you probably already know, people&quot;),
reply: false,
retweet: false,
};
println!(&quot;1 new tweet: {}&quot;, tweet.summarize());
}
</code></pre>
<h2>2、协议的默认实现</h2>
<pre><code>use std::error::Error;
pub trait Summary {
fn summarize(&amp;self) -&gt; String {
&quot;0&quot;.to_string()
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
}
fn main() {
let tweet = Tweet {
username: String::from(&quot;horse_ebooks&quot;),
content: String::from(&quot;of course, as you probably already know, people&quot;),
reply: false,
retweet: false,
};
println!(&quot;1 new tweet: {}&quot;, tweet.summarize());
}
</code></pre>
<h2>3、Trait作为参数(类似多态)</h2>
<pre><code>参数遵守协议
pub fn notify(item: &amp;impl Summary) {}
pub fn notify&lt;T: Summary&gt;(item: &amp;T) {} // 泛型写法
参数遵守多个协议
pub fn notify(item: &amp;(impl Summary + Display)) {}
pub fn notify&lt;T: Summary + Display&gt;(item: &amp;T) {}
where写法简化trait bound
fn some_function&lt;T: Display + Clone, U: Clone + Debug&gt;(t: &amp;T, u: &amp;U) -&gt; i32 {}
fn some_function&lt;T, U&gt;(t: &amp;T, u: &amp;U) -&gt; i32 where T: Display + Clone,U: Clone + Debug {}</code></pre>