impl 方法定义 ​

核心概念 ​

impl 块(Implementation Block)用来为结构体或枚举定义行为。Rust 将数据(字段)和行为(方法)分开定义——字段在 struct 或 enum 中声明,方法在 impl 块中定义。一个类型可以有多个 impl 块,用来分组不同职责的方法。impl 块中的函数分为两类:方法(有 self 参数,通过实例调用)和关联函数(没有 self 参数,通过类型名调用)。

rust
struct Rectangle {
    width: f64,
    height: f64,
}

// impl 块为 Rectangle 定义方法
impl Rectangle {
    // 关联函数:通过 Rectangle::new() 调用
    fn new(width: f64, height: f64) -> Self {
        Rectangle { width, height }
    }

    // 方法:通过实例调用
    fn area(&self) -> f64 {
        self.width * self.height
    }

    fn perimeter(&self) -> f64 {
        2.0 * (self.width + self.height)
    }
}

fn main() {
    let rect = Rectangle::new(10.0, 5.0);  // 关联函数
    println!("面积: {:.1}", rect.area());       // 方法
    println!("周长: {:.1}", rect.perimeter());   // 方法
}

impl 块的语法规则 ​

rust
#[derive(Debug)]
struct Counter {
    count: u32,
    limit: u32,
}

// 第一个 impl 块:构造和查询
impl Counter {
    // Self 是当前类型的别名,等价于 Counter
    fn new(limit: u32) -> Self {
        Counter { count: 0, limit }
    }

    fn count(&self) -> u32 {
        self.count
    }

    fn limit(&self) -> u32 {
        self.limit
    }

    fn is_done(&self) -> bool {
        self.count >= self.limit
    }
}

// 第二个 impl 块:操作方法
impl Counter {
    fn increment(&mut self) {
        if self.count < self.limit {
            self.count += 1;
        }
    }

    fn reset(&mut self) {
        self.count = 0;
    }
}

fn main() {
    let mut counter = Counter::new(3);

    while !counter.is_done() {
        counter.increment();
        println!("计数: {}/{}", counter.count(), counter.limit());
    }

    println!("完成!重置...");
    counter.reset();
    println!("重置后: {}", counter.count());
}

方法的自动引用 ​

Rust 在调用方法时会自动添加 &、&mut 或 *,让方法调用的语法更简洁。

rust
#[derive(Debug)]
struct Text {
    content: String,
}

impl Text {
    fn new(s: &str) -> Self {
        Text { content: s.to_string() }
    }

    fn len(&self) -> usize {
        self.content.len()
    }
}

fn main() {
    let t = Text::new("hello");

    // 以下三种写法等价,编译器自动添加 &
    println!("{}", t.len());          // 自动借用
    println!("{}", (&t).len());       // 手动借用
    println!("{}", Text::len(&t));    // 完全限定语法

    // 通过引用调用方法也不需要手动解引用
    let r = &t;
    println!("{}", r.len());          // 自动解引用
}

为枚举定义方法 ​

rust
#[derive(Debug)]
enum Shape {
    Circle(f64),
    Rectangle(f64, f64),
    Triangle(f64, f64, f64),
}

impl Shape {
    fn area(&self) -> f64 {
        match self {
            Shape::Circle(r) => std::f64::consts::PI * r * r,
            Shape::Rectangle(w, h) => w * h,
            Shape::Triangle(a, b, c) => {
                let s = (a + b + c) / 2.0;
                (s * (s - a) * (s - b) * (s - c)).sqrt()
            }
        }
    }

    fn name(&self) -> &str {
        match self {
            Shape::Circle(_) => "圆形",
            Shape::Rectangle(_, _) => "矩形",
            Shape::Triangle(_, _, _) => "三角形",
        }
    }
}

fn main() {
    let shapes = vec![
        Shape::Circle(5.0),
        Shape::Rectangle(4.0, 6.0),
        Shape::Triangle(3.0, 4.0, 5.0),
    ];

    for s in &shapes {
        println!("{}: 面积 = {:.2}", s.name(), s.area());
    }
}

基本示例 ​

rust
#[derive(Debug)]
struct BankAccount {
    owner: String,
    balance: f64,
    history: Vec<String>,
}

impl BankAccount {
    fn new(owner: &str) -> Self {
        BankAccount {
            owner: owner.to_string(),
            balance: 0.0,
            history: Vec::new(),
        }
    }

    fn deposit(&mut self, amount: f64) {
        if amount > 0.0 {
            self.balance += amount;
            self.history.push(format!("存入 ¥{:.2}", amount));
        }
    }

    fn withdraw(&mut self, amount: f64) -> bool {
        if amount > 0.0 && amount <= self.balance {
            self.balance -= amount;
            self.history.push(format!("取出 ¥{:.2}", amount));
            true
        } else {
            false
        }
    }

    fn balance(&self) -> f64 {
        self.balance
    }

    fn display(&self) {
        println!("账户: {}, 余额: ¥{:.2}", self.owner, self.balance);
        if !self.history.is_empty() {
            println!("交易记录:");
            for record in &self.history {
                println!("  {}", record);
            }
        }
    }
}

fn main() {
    let mut account = BankAccount::new("张三");
    account.deposit(5000.0);
    account.withdraw(1200.0);
    account.deposit(800.0);
    account.display();
}

常见问题 ​

问题一:一个类型可以有多少个 impl 块?

没有数量限制。可以用多个 impl 块按职责分组方法。trait 实现也需要单独的 impl 块。

问题二:impl 块里可以定义常量吗?

可以。用 const 定义关联常量:const MAX: u32 = 100;,通过 Type::MAX 访问。

问题三:Self 和类型名有什么区别?

Self 是语法糖,在 impl 块中总是等价于当前类型名。使用 Self 的好处是类型名修改时不需要同步修改 impl 块内的代码。

问题四:方法可以和字段同名吗?

可以。Rust 通过是否有括号来区分:instance.field 访问字段,instance.field() 调用方法。

适用场景 ​

  • 数据封装:将字段设为私有,通过方法访问
  • 行为定义:为类型添加计算、操作、转换等行为
  • 构造器:关联函数提供多种创建实例的方式
  • 方法分组:多个 impl 块按职责组织代码

注意事项 ​

  • 数据(字段)在 struct/enum 中定义,行为(方法)在 impl 块中定义
  • 一个类型可以有多个 impl 块
  • Self 是当前类型的别名
  • Rust 自动添加引用来匹配方法签名
  • impl 块中可以定义方法、关联函数和关联常量
  • 方法和字段可以同名,通过括号区分

总结 ​

impl 块是 Rust 中为类型定义行为的唯一方式。它将数据和行为分离——字段在 struct/enum 中声明,方法在 impl 块中定义。一个类型可以有多个 impl 块来分组不同职责的方法。方法以 self 为第一个参数,关联函数不需要 self。Rust 的自动引用机制让方法调用语法简洁自然。Self 作为当前类型的别名,在返回类型和构造函数中广泛使用。