Rust泛型特征、集合类型

目录泛型与特征泛型Generics特征Trait特征对象进一步深入特征集合类型动态数组VectorKV存储HashMap泛型与特征泛型(Generics)基础概念定义:泛型允许我们编写可以处理多种类型的代码。语法:使用尖括号<>来指定类型参数。fn

目录


泛型与特征

泛型 (Generics)

基础概念

  • 定义:泛型允许我们编写可以处理多种类型的代码。
  • 语法:使用尖括号<>来指定类型参数。
fn identity&lt;T>(arg: T) -> T {
    arg
}

fn main() {
    let output = identity(String::from("Hello World"));
    println!("The output is: {}", output);
}

在这个例子中,identity函数接受一个类型参数T,这意味着它可以接受任何类型的输入,并返回相同类型的值。

使用约束

  • 添加约束:可以为类型参数添加约束,确保其满足某些条件。
  • 示例:要求类型必须实现某个特定的trait。
trait ExampleTrait {
    fn example_method(&self);
}

struct ExampleStruct;

impl ExampleTrait for ExampleStruct {
    fn example_method(&self) {
        println!("Example method called");
    }
}

fn requires_example_trait&lt;T: ExampleTrait>(t: T) {
    t.example_method();
}

fn main() {
    let example = ExampleStruct;
    requires_example_trait(example);
}

特征 (Traits)

定义

  • 定义:特征定义了一组方法签名,描述了某种行为。
  • 语法:使用trait关键字定义。
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:trait可以要求其实现者也实现其他trait。

trait Display: std::fmt::Display {}
impl&lt;T: std::fmt::Display> Display for T {}

fn display&lt;T: Display...

剩余50%的内容订阅专栏后可查看

点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论