Rust的面向对象特性

目录Rust的面向对象特性面向对象特点trait对象面向对象设计模式实现Rust的面向对象特性Rust的面向对象特性Rust的面向对象特点Rust并没有传统意义上的面向对象编程(OOP)的概念,但它通过组合和一些高级特性(如trait和泛型)实现了类似OOP

目录


Rust的面向对象特性

Rust 的面向对象特性

Rust 的面向对象特点

Rust 并没有传统意义上的面向对象编程(OOP)的概念,但它通过组合和一些高级特性(如 trait 和泛型)实现了类似 OOP 的功能。

结构体(Structs)

定义结构体 定义结构体:使用 struct 关键字定义结构体。

struct Person {
    name: String,
    age: u32,
}

impl Person {
    fn new(name: String, age: u32) -> Self {
        Person { name, age }
    }
}

fn main() {
    let person = Person::new(String::from("Alice"), 30);
    println!("Name: {}, Age: {}", person.name, person.age);
}

实现(Impl)

实现方法 实现方法:使用 impl 关键字为结构体实现方法。

struct Person {
    name: String,
    age: u32,
}

impl Person {
    fn new(name: String, age: u32) -> Self {
        Person { name, age }
    }

    fn introduce(&self) {
        println!("Hello, my name is {} and I am {} years old.", self.name, self.age);
    }
}

fn main() {
    let person = Person::new(String::from("Alice"), 30);
    person.introduce();
}

Trait 对象

定义 Trait 定义 Trait:使用 trait 关键字定义一组行为。

trait Animal {
    fn make_sound(&self);
}

struct Dog {
    name: String,
}

impl Animal for Dog {
    fn make_sound(&self) {
        println!("Woof!");
    }
}

struct Cat {
    name: String,
}

impl Animal for Cat {
    fn make_sound(&self) {
        println!("Meow!");
    }
}

fn make_animal_sound(animal: &dyn Animal) {
    animal.make_sound();
}

fn main() {
    let dog = Dog { name: String::from("Buddy") };
    let cat = Cat { name: String::from("Whiskers") };

    make_an animal_sound(&dog);
    make_animal_sound(&cat);
}

泛型和生命周期

泛型 泛型:使用 <T> 关键字定义泛型类型。

struct Box<T>(T);

impl<T> Box<T> {
    fn new(item: T) -> Self {
        Box(item)
    }
}

fn main() {
    let box_i32 = Box::new(5);
    let box_str = Box::new(String::from("Hello"));
}

生命周期 生命周期:确保借用不会超出作用域。


struct Message<'a> {
    text: &'a str,
}

impl<'a> Message<'a> {
    fn new(text: &'a str) -> Self {
        Message { text }
    }

    fn display(&self) {
        println!("Message: {}", self.text);
    }
}

fn main() {
    let text = String::from("Hello, wor...

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

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

0 条评论

请先 登录 后评论