显示页面讨论过去修订反向链接回到顶部 本页面只读。您可以查看源文件,但不能更改它。如果您觉得这是系统错误,请联系管理员。 # 20. use 与路径管理 ## 学习目标 - 使用 `use` 将路径引入作用域。 - 理解 `crate`、`self`、`super` 的区别。 - 使用 `pub use` 重新导出。 - 避免 `use` 引入带来的命名冲突。 ## 20.1 `use` 简化路径 反复写 `crate::front_of_house::hosting::add_to_waitlist` 很麻烦。可以用 `use` 把路径引入作用域: ```rust mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } use crate::front_of_house::hosting; pub fn eat_at_restaurant() { hosting::add_to_waitlist(); } ``` 也可以引入具体函数: ```rust use crate::front_of_house::hosting::add_to_waitlist; pub fn eat_at_restaurant() { add_to_waitlist(); } ``` ## 20.2 习惯用法 通常习惯把父模块引入作用域,而不是具体函数,这样更清晰: ```rust use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert(1, 2); } ``` ## 20.3 `as` 关键字 如果两个模块有同名项,可以用 `as` 重命名: ```rust use std::fmt::Result; use std::io::Result as IoResult; fn function1() -> Result { } fn function2() -> IoResult<()> { } ``` ## 20.4 `pub use` 重新导出 `use` 只在当前模块有效。如果希望外部调用者也能使用,需要 `pub use`: ```rust mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } pub use crate::front_of_house::hosting; pub fn eat_at_restaurant() { hosting::add_to_waitlist(); } ``` 这样,`hosting` 在 crate 外部也可以直接访问。 ## 20.5 `crate`、`self`、`super` - `crate`:根模块。 - `self`:当前模块。 - `super`:父模块。 ```rust fn serve_order() {} mod back_of_house { fn fix_incorrect_order() { cook_order(); super::serve_order(); // 访问父模块的函数 } fn cook_order() {} } ``` ## 20.6 嵌套路径和 glob 多个来自同一模块的 `use` 可以合并: ```rust use std::{cmp::Ordering, io}; ``` 引入模块中所有公共项: ```rust use std::collections::*; ``` > glob 引入要慎用,容易导致命名冲突和可读性下降。 ## 20.7 小结 | 语法 | 含义 | | `use a::b` | 引入 `b` 到当前作用域 | | `use a::b as c` | 重命名为 `c` | | `pub use a::b` | 重新导出,让外部也能使用 | | `crate::` | 根模块 | | `self::` | 当前模块 | | `super::` | 父模块 | | `use std::io::*` | 引入所有公共项 | ## 20.8 思考题 1. `use` 和 `pub use` 有什么区别? 2. 什么时候应该使用 `as` 重命名? 3. 尝试用 `super` 在一个子模块中调用父模块的函数。 登录 Detach Close 该主题尚不存在 您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。 rust/use_与路径管理.txt 最后更改: 2026/08/12 23:35由 张叶安 登录