3.5 Rust Generic Types, Traits, and Lifetimes
阿新 • • 發佈:2020-11-16
Every programming language has tools for effectively handling the duplication of concepts. In Rust, one such tool isgenerics. Generics are abstract stand-ins for concrete types or other properties.
泛型的作用:降低程式碼冗餘
- Identify duplicate code.
- Extract the duplicate code into the body of the function and specify the inputs and return values of that code in the function signature.
- Update the two instances of duplicated code to call the function instead.
Traits: Defining Shared Behavior
Atraittells the Rust compiler about 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 can be any type that has certain behavior.
Note: Traits are similar to a feature often calledinterfacesin other languages, although with some differences.
#![allow(unused)] pub trait Person { fn food(&self) -> String; fn eat(&self) -> String { format!("(eat {}...)", self.food()) } } pub struct Teacher { pub name: String, } impl Personfor Teacher { fn food(&self) -> String { format!("{}", "麵包") } } pub struct Student { pub username: String, pub age: i8, } impl Person for Student { fn food(&self) -> String { format!("{}", "水果") } } pub fn test(){ let tch = Teacher { name: String::from("a01"), }; println!("teacher: {}", tch.eat()); let st = Student { username: String::from("Penguins win the Stanley Cup Championship!"), age: 12, }; println!("student: {}", st.eat()); }
mod tra; fn main() { println!("----------------"); tra::tra1::test(); }
輸出
----------------
teacher: (eat 麵包...)
student: (eat 水果...)