Menu
CoddyTech

获取方法

本课属于 Coddy Rust 学习旅程的“面向对象编程”单元。第 11 课,共 61 课。

使用私有字段后,外部代码无法直接访问结构体的数据。但有时,你需要允许其他人读取数据,同时不让他们修改数据。这时就可以使用getter 方法。

getter 只是一个返回私有字段引用的公共方法:

// wallet.rs
pub struct Wallet {
    balance: f64,
}

impl Wallet {
    pub fn new(initial: f64) -> Wallet {
        Wallet { balance: initial }
    }
    
    pub fn balance(&self) -> f64 {
        self.balance
    }
}

balance() 方法接收 &self(只读访问),并返回私有字段的值。在 Rust 中,getter 通常直接以字段名命名:不需要 get_ 前缀。

现在,外部代码可以通过这个方法读取余额:

// main.rs
mod wallet;
use wallet::Wallet;

fn main() {
    let w = Wallet::new(100.0);
    println!("Balance: {}", w.balance());  // 能运行!
}

对于包含自有数据的字段(如 String),你通常会返回一个引用,以避免不必要的复制:

pub fn name(&self) -> &String {
    &self.name
}

getter 让你能够在保护字段本身的同时,受控地读取数据。结构体仍然掌管自己的数据:外部代码可以查看,但不能修改。

challenge icon

挑战

简单

让我们构建一个用户资料系统,演示 getter 方法如何提供对私有数据的受控读取访问。

你将创建两个文件来组织代码:

  • profile.rs:定义一个包含两个私有字段的 UserProfile 结构体:username(String)和 age(u32)。结构体本身应该是公开的,但字段应保持私有。实现一个公开的 new 构造函数,接收用户名和年龄。然后添加两个 getter 方法:
    • username:返回用户名的引用(&String)
    • age:返回年龄值(u32)
  • main.rs:引入你的 profile 模块,创建一个 UserProfile,并使用 getter 方法打印用户信息。

请记住,在 Rust 中,getter 通常以字段本身命名:不需要添加 get_ 前缀。对于 String 字段,返回引用可以避免不必要的复制。

你的输出应遵循以下确切格式:

Username: {username}
Age: {age}

例如,如果你创建的资料用户名为 "alice",年龄为 25,输出将是:

Username: alice
Age: 25

你将收到两个输入:用户名和年龄。

亲手试试

mod profile;

use profile::UserProfile;

fn main() {
    let mut input1 = String::new();
    std::io::stdin().read_line(&mut input1).expect("Failed to read line");
    let username = input1.trim().to_string();

    let mut input2 = String::new();
    std::io::stdin().read_line(&mut input2).expect("Failed to read line");
    let age: u32 = input2.trim().parse().expect("Failed to parse age");

    // TODO: 使用构造函数创建一个 UserProfile

    // TODO: 使用 getter 方法打印用户名和年龄
    // 格式:
    // Username: {username}
    // Age: {age}
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向对象编程中的所有课

自己练习: Rust 在线编译器