Rust:深入理解结构体(Structs)与实现块(impl Blocks)——附示例

更新于 2026-01-15

在 Rust 中,结构体(structs)用于创建自定义数据类型。为了给这些类型添加方法,Rust 使用 impl 块(实现块)。本博客将深入探讨 Rust 中结构体和 impl 块的用法,并提供十个由浅入深的示例。


定义并实例化一个结构体

struct Rectangle {
    width: u32,
    height: u32,
}

let rect1 = Rectangle { width: 30, height: 50 };

添加一个函数

struct Rectangle {
    width: u32,
    height: u32,
}

fn area(rectangle: &Rectangle) -> u32 {
    rectangle.width * rectangle.height
}

let rect1 = Rectangle { width: 30, height: 50 };
println!("The area of the rectangle is {} square pixels.", area(&rect1));

使用 impl 添加关联方法

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

let rect1 = Rectangle { width: 30, height: 50 };
println!("The area of the rectangle is {} square pixels.", rect1.area());

添加更多方法

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

let rect1 = Rectangle { width: 30, height: 50 };
let rect2 = Rectangle { width: 10, height: 40 };
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));

关联函数(Associated Functions)

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn square(size: u32) -> Rectangle {
        Rectangle { width: size, height: size }
    }
}

let sq = Rectangle::square(3);

多个 impl

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

impl Rectangle {
    fn square(size: u32) -> Rectangle {
        Rectangle { width: size, height: size }
    }
}

使用元组结构体(Tuple Structs)

struct Color(u8, u8, u8);

let white = Color(255, 255, 255);

为元组结构体定义方法

struct Color(u8, u8, u8);

impl Color {
    fn red(&self) -> u8 {
        self.0
    }
}

let red = Color(255, 0, 0);
println!("Red value is {}", red.red());

继承与组合

Rust 不支持继承,但支持组合(composition)。

struct Point {
    x: f64,
    y: f64,
}

struct Line {
    start: Point,
    end: Point,
}

impl Line {
    fn length(&self) -> f64 {
        let dx = self.start.x - self.end.x;
        let dy = self.start.y - self.end.y;
        (dx * dx + dy * dy).sqrt()
    }
}

let p1 = Point { x: 1.0, y: 1.0 };
let p2 = Point { x: 4.0, y: 5.0 };
let line = Line { start: p1, end: p2 };
println!("Line length is {}", line.length());

单元类结构体(Unit-Like Struct)

单元类结构体在某些场景下非常有用,例如当你需要为某个类型实现 trait,但该类型本身不需要存储任何数据时。

struct MyStruct;

impl MyStruct {
    fn hello() {
        println!("Hello from MyStruct!");
    }
}

MyStruct::hello();

在此示例中,MyStruct 不包含任何数据。它仅作为 hello 函数的上下文存在。这种设计可用于对相关函数进行分组。


关联函数(通常用作构造函数)

struct Circle {
    radius: f64,
}

impl Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * (self.radius * self.radius)
    }

    // 一个用于创建新 Circle 的关联函数。这充当构造函数。
    fn new(radius: f64) -> Circle {
        Circle { radius }
    }
}

fn main() {
    let circ = Circle::new(10.0);
    println!("The area of the circle is {:.2}", circ.area());
}

在此示例中,new 是一个关联函数,因为它与 Circle 结构体相关联,但不接收 self 参数。这类函数通常用于创建结构体的新实例。在这里,它被用作 Circle 的构造函数。