Rust 面向对象学习笔记

目录

简介

Rust 是一种内存安全、并发性高的系统级编程语言,具有功能强大的类型安全性和模式匹配机制。Rust 的设计既具备面向对象编程的特征,也支持函数式编程风格。

在 Rust 中,对于对象的管理和处理,通常使用结构体 struct 进行操作。struct 可以被看作是一组相关字段的结合体,具有独立的特性和方法。

下面将介绍 Rust 中的面向对象编程概念,并通过实例演示如何在 Rust 中实现面向对象编程。

面向对象编程概念

Rust 中的面向对象编程概念包括:

  • 封装
  • 继承
  • 多态

封装

封装是面向对象编程的基本概念之一,它指的是将数据和相关操作封装在一个单元中,以便控制和保护数据。在 Rust 中,封装可以通过结构体 struct 和特性 trait 实现。

结构体 struct 定义了一个新的数据类型,可以包含对数据进行操作的函数。例如,下面定义了一个 Rectangle 结构体:

rustCopy Code
struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } } let rect = Rectangle { width: 3, height: 4 }; println!("The area of the rectangle is {} square pixels.", rect.area());

这个例子中,Rectangle 结构体包含两个字段 width 和 height,以及一个方法 area,用于计算矩形的面积。通过 impl 把方法与结构体关联起来,实现封装。

继承

继承是面向对象编程中常见的概念,指的是从已有的类或结构体派生出新的类或结构体,并且新的类或结构体具备原类或结构体的属性和方法。在 Rust 中,通过继承 trait 实现继承。

trait 是一种抽象类型,它定义了一组方法,但是没有任何默认行为。因此,当其他类型实现某个 trait 时,它们需要提供自己的实现。例如:

rustCopy Code
trait Animal { fn sound(&self); } struct Dog {} impl Animal for Dog { fn sound(&self) { println!("The dog says 'woof woof!'"); } } let dog = Dog {}; dog.sound();

在这个例子中,定义了一个 Animal trait,它规定了一个 sound 方法。然后定义了一个 Dog 结构体,并为其实现了 Animal trait,提供了一个 sound 方法的具体实现。通过这种方式实现继承。

多态

多态是面向对象编程的重要概念之一,它指的是同一方法在不同的类型中有不同的行为。在 Rust 中,通过 trait 和泛型实现多态。

rustCopy Code
trait Shape { fn area(&self) -> f64; } struct Rectangle { width: f64, height: f64, } struct Circle { radius: f64, } impl Shape for Rectangle { fn area(&self) -> f64 { self.width * self.height } } impl Shape for Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } fn print_area(shape: &dyn Shape) { println!("Area of the shape is {}", shape.area()); } let rect = Rectangle { width: 3.0, height: 4.0 }; let circle = Circle { radius: 5.0 }; print_area(&rect); print_area(&circle);

在这个例子中,定义了一个 Shape trait,规定了一个 area 方法。然后定义了一个 Rectangle 结构体和一个 Circle 结构体,并为其分别实现 Shape trait 的 area 方法。最后定义了一个 print_area 函数,接受任何实现了 Shape trait 的类型,并输出其面积。

示例代码

下面是一个完整的 Rust 面向对象编程示例代码:

rustCopy Code
trait Shape { fn area(&self) -> f64; } struct Rectangle { width: f64, height: f64, } struct Circle { radius: f64, } impl Shape for Rectangle { fn area(&self) -> f64 { self.width * self.height } } impl Shape for Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } fn print_area(shape: &dyn Shape) { println!("Area of the shape is {}", shape.area()); } fn main() { let rect = Rectangle { width: 3.0, height: 4.0 }; let circle = Circle { radius: 5.0 }; print_area(&rect); print_area(&circle); }

输出结果如下:

Copy Code
Area of the shape is 12 Area of the shape is 78.53981633974483