03-方法

方法 — Rust By Example

译文 · 基于 Rust By Example

原文链接: https://doc.rust-lang.org/stable/rust-by-example/scope/lifetime/methods.html

方法

方法的标注和函数类似:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
struct Owner(i32);

impl Owner {
    // 标注生命周期,就像独立的函数一样。
    fn add_one<'a>(&'a mut self) { self.0 += 1; }
    fn print<'a>(&'a self) {
        println!("`print`: {}", self.0);
    }
}

fn main() {
    let mut owner  = Owner(18);

    owner.add_one();
    owner.print();
}

译注:方法一般是不需要标明生命周期的,因为 self 的生命周期会赋给所有的输出生命周期参数,详见 TRPL。

参见:

方法

最后修改 August 21, 2026: 更新 (76fc81a2e)