目录

20. use 与路径管理

学习目标

20.1 `use` 简化路径

反复写 crate::front_of_house::hosting::add_to_waitlist 很麻烦。可以用 use 把路径引入作用域:

snippet.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();
}

也可以引入具体函数:

snippet.rust
use crate::front_of_house::hosting::add_to_waitlist;
 
pub fn eat_at_restaurant() {
    add_to_waitlist();
}

20.2 习惯用法

通常习惯把父模块引入作用域,而不是具体函数,这样更清晰:

snippet.rust
use std::collections::HashMap;
 
fn main() {
    let mut map = HashMap::new();
    map.insert(1, 2);
}

20.3 `as` 关键字

如果两个模块有同名项,可以用 as 重命名:

snippet.rust
use std::fmt::Result;
use std::io::Result as IoResult;
 
fn function1() -> Result { }
fn function2() -> IoResult<()> { }

20.4 `pub use` 重新导出

use 只在当前模块有效。如果希望外部调用者也能使用,需要 pub use:

snippet.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`

snippet.rust
fn serve_order() {}
 
mod back_of_house {
    fn fix_incorrect_order() {
        cook_order();
        super::serve_order(); // 访问父模块的函数
    }
 
    fn cook_order() {}
}

20.6 嵌套路径和 glob

多个来自同一模块的 use 可以合并:

snippet.rust
use std::{cmp::Ordering, io};

引入模块中所有公共项:

snippet.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 在一个子模块中调用父模块的函数。