use 导入声明 ​

什么是 use ​

use 关键字把模块中的项引入当前作用域,这样就不用每次都写完整的模块路径了。它就像创建一个快捷方式——把远处的项"拉"到眼前直接使用。

rust
// 不用 use:每次都写完整路径
fn without_use() {
    let mut map = std::collections::HashMap::new();
    map.insert("key", "value");
    let set = std::collections::HashSet::<i32>::new();
}

// 用 use:先导入,后面直接用名字
use std::collections::HashMap;
use std::collections::HashSet;

fn with_use() {
    let mut map = HashMap::new();
    map.insert("key", "value");
    let set = HashSet::<i32>::new();
}

fn main() {
    with_use();
}

基本语法 ​

rust
// 导入单个项
use std::fmt::Display;

// 导入模块本身
use std::collections;

// 导入后可以直接用名字
fn show(item: &impl Display) {
    println!("{}", item);
}

fn main() {
    show(&42);

    // 导入了模块,用 模块名::项名 访问
    let mut map = collections::HashMap::new();
    map.insert(1, "one");
}

嵌套导入 ​

当需要从同一个模块导入多个项时,可以用花括号合并成一条 use 语句。

rust
// 分开写
use std::io::Read;
use std::io::Write;
use std::io::BufReader;

// 合并写(推荐)
use std::io::{Read, Write, BufReader};

// 同时导入模块本身和它的项
use std::collections::{self, HashMap, HashSet};
// 等价于:
// use std::collections;
// use std::collections::HashMap;
// use std::collections::HashSet;

// 多层嵌套也可以
use std::io::{self, Read, Write};

fn main() {
    let mut map = HashMap::new();
    map.insert("rust", 100);

    let set = HashSet::<i32>::new();
    println!("HashMap: {:?}, HashSet: {:?}", map, set);
}

通配符导入 ​

use module::* 把模块中所有公开项导入当前作用域。一般不推荐在正式代码中使用(可能导致命名冲突),但在测试和 prelude 模式中很常见。

rust
mod shapes {
    pub const PI: f64 = std::f64::consts::PI;

    pub fn circle_area(r: f64) -> f64 {
        PI * r * r
    }

    pub fn rect_area(w: f64, h: f64) -> f64 {
        w * h
    }

    pub fn triangle_area(base: f64, height: f64) -> f64 {
        0.5 * base * height
    }
}

fn main() {
    // 通配符导入:所有公开项都可以直接用
    use shapes::*;

    println!("PI = {:.4}", PI);
    println!("圆面积(r=5): {:.2}", circle_area(5.0));
    println!("矩形面积(3x4): {:.2}", rect_area(3.0, 4.0));
    println!("三角形面积(6,8): {:.2}", triangle_area(6.0, 8.0));
}

use 的作用域 ​

use 导入的项只在当前作用域内有效。

rust
mod tools {
    pub fn hammer() { println!("锤子"); }
    pub fn saw() { println!("锯子"); }
}

fn scoped_example() {
    // 在函数内部 use,只在这个函数里有效
    use tools::hammer;
    hammer();
}

fn another_function() {
    // hammer();  // 编译错误:hammer 不在这个函数的作用域中
    tools::hammer();  // 用完整路径可以
}

fn main() {
    scoped_example();
    another_function();
}

use 与模块路径 ​

rust
mod app {
    pub mod models {
        pub struct User {
            pub name: String,
        }
    }

    pub mod services {
        // 在模块内部用 use 导入其他模块的项
        // crate:: 绝对路径
        use crate::app::models::User;

        pub fn create_user(name: &str) -> User {
            User { name: name.to_string() }
        }
    }

    pub mod handlers {
        // super:: 相对路径
        use super::models::User;
        use super::services;

        pub fn handle() {
            let user = services::create_user("张三");
            println!("创建用户:{}", user.name);
        }
    }
}

fn main() {
    app::handlers::handle();
}

导入惯例 ​

Rust 社区对 use 有一些约定俗成的惯例:

rust
// 惯例一:函数通常导入到父模块级别
use std::collections::HashMap;
// 然后用 HashMap::new(),而不是 use std::collections::HashMap::new

// 惯例二:类型(结构体、枚举)直接导入
use std::io::Error;
// 然后直接用 Error

// 惯例三:trait 直接导入(否则不能用它的方法)
use std::io::Write;

// 惯例四:同名项用父模块区分
use std::fmt;
use std::io;

fn fmt_function(value: &impl fmt::Display) -> fmt::Result {
    // 用 fmt::Result 和 io::Result 区分同名类型
    Ok(())
}

fn io_function() -> io::Result<()> {
    Ok(())
}

fn main() {
    let _ = fmt_function(&42);
    let _ = io_function();
}

基本示例 ​

rust
use std::collections::HashMap;

// 定义应用模块
mod inventory {
    pub struct Item {
        pub name: String,
        pub quantity: u32,
        pub price: f64,
    }

    impl Item {
        pub fn new(name: &str, qty: u32, price: f64) -> Self {
            Item {
                name: name.to_string(),
                quantity: qty,
                price,
            }
        }

        pub fn total_value(&self) -> f64 {
            self.quantity as f64 * self.price
        }
    }
}

// 在 main 中导入使用
use inventory::Item;

fn print_report(items: &[Item]) {
    println!("{:<15} {:>5} {:>10} {:>12}", "名称", "数量", "单价", "总价");
    println!("{}", "-".repeat(45));

    let mut total = 0.0;
    for item in items {
        let value = item.total_value();
        total += value;
        println!("{:<15} {:>5} {:>10.2} {:>12.2}",
            item.name, item.quantity, item.price, value);
    }

    println!("{}", "-".repeat(45));
    println!("{:<33} {:>12.2}", "合计", total);
}

fn main() {
    let items = vec![
        Item::new("笔记本", 50, 8.5),
        Item::new("签字笔", 200, 2.0),
        Item::new("文件夹", 30, 15.0),
        Item::new("订书机", 10, 25.0),
    ];

    print_report(&items);

    // 用 HashMap 按名称索引
    let mut index: HashMap<&str, &Item> = HashMap::new();
    for item in &items {
        index.insert(&item.name, item);
    }

    if let Some(item) = index.get("签字笔") {
        println!("\n查询:{} 库存 {} 件", item.name, item.quantity);
    }
}

常见问题 ​

问题一:use 放在哪里?

通常放在文件或模块的顶部,mod 声明之后。也可以放在函数内部(局部导入),作用域仅限于该函数。

问题二:两个模块有同名的项怎么办?

用 as 重命名(下一节会讲),或者只导入到父模块级别用 模块名::项名 来区分。

rust
use std::fmt;
use std::io;

// 用模块名区分同名类型
fn example() -> Result<(), Box<dyn std::error::Error>> {
    let _f: fmt::Result = Ok(());
    let _i: io::Result<()> = Ok(());
    Ok(())
}

fn main() {
    let _ = example();
}

问题三:use * 会导入私有项吗?

不会。use module::* 只导入 pub 的项,私有项不受影响。

问题四:use 会有运行时开销吗?

没有。use 纯粹是编译期的名字解析,不生成任何运行时代码。

适用场景 ​

  • 简化路径:避免反复写长长的模块路径
  • 导入 trait:使用 trait 的方法前需要先 use 该 trait
  • 代码顶部集中声明:让依赖关系一目了然
  • 测试中通配符导入:use super::* 快速导入被测模块的所有项

注意事项 ​

  • use 只在当前作用域内生效
  • 导入 trait 后才能使用该 trait 的方法
  • 避免在正式代码中使用 use module::*(容易命名冲突)
  • 同名项用父模块路径或 as 重命名来区分
  • use 没有运行时开销
  • 惯例:类型直接导入名字,同名类型导入父模块来区分
  • 嵌套导入 use module::{A, B, C} 比多行 use 更简洁

总结 ​

use 把模块中的项引入当前作用域,让你不用每次都写完整路径。它支持嵌套导入(use module::{A, B})、同时导入模块和项(use module::{self, Item})和通配符导入(use module::*)。use 是编译期的名字解析,没有运行时开销。Rust 的惯例是在文件顶部集中声明 use,类型直接导入名字,同名类型通过保留父模块路径来区分。使用 trait 的方法前必须先导入该 trait。