04-抽象与选择性暴露

抽象与选择性暴露 — Rust 语言之旅

内容来源 · Tour of Rust / Rust 语言之旅

原文链接: https://tourofrust.com/77_zh-cn.html

抽象与选择性暴露

Rust 可以隐藏对象的内部实现细节。

默认情况下,字段和方法只有它们所属的模块才可访问。

pub 关键字可以将字段和方法暴露给模块外的访问者。

示例代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
struct SeaCreature {
    pub name: String,
    noise: String,
}

impl SeaCreature {
    pub fn get_sound(&self) -> &str {
        &self.noise
    }
}

fn main() {
    let creature = SeaCreature {
        name: String::from("Ferris"),
        noise: String::from("blub"),
    };
    println!("{}", creature.get_sound());
}
最后修改 August 21, 2026: 更新 (76fc81a2e)