目录泛型与特征泛型Generics特征Trait特征对象进一步深入特征集合类型动态数组VectorKV存储HashMap泛型与特征泛型(Generics)基础概念定义:泛型允许我们编写可以处理多种类型的代码。语法:使用尖括号<>来指定类型参数。fn
基础概念
fn identity<T>(arg: T) -> T {
arg
}
fn main() {
let output = identity(String::from("Hello World"));
println!("The output is: {}", output);
}
在这个例子中,identity函数接受一个类型参数T,这意味着它可以接受任何类型的输入,并返回相同类型的值。
使用约束
trait ExampleTrait {
fn example_method(&self);
}
struct ExampleStruct;
impl ExampleTrait for ExampleStruct {
fn example_method(&self) {
println!("Example method called");
}
}
fn requires_example_trait<T: ExampleTrait>(t: T) {
t.example_method();
}
fn main() {
let example = ExampleStruct;
requires_example_trait(example);
}
定义
trait Summary {
fn summarize(&self) -> String;
}
struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}
fn notify(item: &impl Summary) {
println!("Breaking news: {}", item.summarize());
}
fn main() {
let article = NewsArticle {
headline: String::from("Penguins win the Stanley Cup Championship!"),
location: String::from("Pittsburgh, PA, USA"),
author: String::from("Iceburgh"),
content: String::from(
"The Pittsburgh Penguins once again are the best \
hockey team in NHL.",
),
};
notify(&article);
}
&dyn TraitName形式。trait Animal {
fn make_sound(&self);
}
struct Dog;
impl Animal for Dog {
fn make_sound(&self) {
println!("Woof!");
}
}
struct Cat;
impl Animal for Cat {
fn make_sound(&self) {
println!("Meow!");
}
}
fn animal_sound(animal: &dyn Animal) {
animal.make_sound();
}
fn main() {
let dog = Dog;
let cat = Cat;
animal_sound(&dog);
animal_sound(&cat);
}
默认实现
trait定义时提供默认实现。trait Draw {
fn draw(&self);
fn default_draw(&self) {
println!("Default drawing behavior");
}
}
struct Screen;
impl Draw for Screen {
fn draw(&self) {
println!("Drawing Screen");
}
}
fn main() {
let screen = Screen;
screen.draw();
screen.default_draw();
}
高阶trait
trait Display: std::fmt::Display {}
impl<T: std::fmt::Display> Display for T {}
fn display<T: Display... 如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!