leisurely8rust


01.特征Trait

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

页面列表

ITEM_HTML