use 将路径引入作用域。crate、self、super 的区别。pub use 重新导出。use 引入带来的命名冲突。
反复写 crate::front_of_house::hosting::add_to_waitlist 很麻烦。可以用 use 把路径引入作用域:
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(); }
也可以引入具体函数:
use crate::front_of_house::hosting::add_to_waitlist; pub fn eat_at_restaurant() { add_to_waitlist(); }
通常习惯把父模块引入作用域,而不是具体函数,这样更清晰:
use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert(1, 2); }
如果两个模块有同名项,可以用 as 重命名:
use std::fmt::Result; use std::io::Result as IoResult; fn function1() -> Result { } fn function2() -> IoResult<()> { }
use 只在当前模块有效。如果希望外部调用者也能使用,需要 pub use:
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 外部也可以直接访问。
crate:根模块。self:当前模块。super:父模块。fn serve_order() {} mod back_of_house { fn fix_incorrect_order() { cook_order(); super::serve_order(); // 访问父模块的函数 } fn cook_order() {} }
多个来自同一模块的 use 可以合并:
use std::{cmp::Ordering, io};
引入模块中所有公共项:
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::* | 引入所有公共项 |
use 和 pub use 有什么区别?as 重命名?super 在一个子模块中调用父模块的函数。