rust:use_与路径管理

20. use 与路径管理

  • 使用 use 将路径引入作用域。
  • 理解 crate、self、super 的区别。
  • 使用 pub use 重新导出。
  • 避免 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();
}

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

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

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

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

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 外部也可以直接访问。

  • crate:根模块。
  • self:当前模块。
  • super:父模块。
snippet.rust
fn serve_order() {}
 
mod back_of_house {
    fn fix_incorrect_order() {
        cook_order();
        super::serve_order(); // 访问父模块的函数
    }
 
    fn cook_order() {}
}

多个来自同一模块的 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::* 引入所有公共项
  1. use 和 pub use 有什么区别?
  2. 什么时候应该使用 as 重命名?
  3. 尝试用 super 在一个子模块中调用父模块的函数。

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • rust/use_与路径管理.txt
  • 最后更改: 2026/08/12 23:35
  • 由 张叶安