`use` 和 `pub use` 有什么区别?

问题描述 投票:0回答:2

Rust 的文档中有一个我不明白的地方:就是

pub
前面的
use
关键字,它有什么作用? 这是 Rust 文档中的示例(Here):

mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {
            println!("Added to waitlist");
        }
    }
}

pub use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
    hosting::add_to_waitlist();
    hosting::add_to_waitlist();
}

当我尝试制作一个与之交互的主程序时,我想出了:

use tests::eat_at_restaurant;

fn main() {
    eat_at_restaurant();
}

但是当我删除

use
关键字时,它会执行相同的操作,并且在任何情况下我都无法从 main 调用
hosting::add_to_waitlist
,那么这里会发生什么?如果我不输入
pub
关键字有什么区别?

rust
2个回答
23
投票

use
用于将项目导入到当前模块中,
pub use
允许我们(不仅可以导入,还可以)重新导出该项目。

以下是需要

pub use
的示例:

// src/foo/mod.rs

mod bar;
pub use bar::item;
// src/foo/bar.rs

pub fn item() {
    println!("Hello, world!");
}
// src/main.rs

mod foo;
use foo::item;

fn main() {
    item();
}

如果我们使用普通的

use
那么
item
将无法访问。但是,由于我们添加了
pub
关键字,
item
现在可用于所有使用
nested
模块的模块。

我们称之为“重新导出”,因为

item
实际上并未在
foo
中定义,而是
foo
item
“重新导出”
foo::bar


0
投票

我们就不能

use foo::bar::item
吗?我们做
pub use bar::item
来隐藏
bar
? 用户如何知道可以通过
item
而不是
use foo::item
访问
use foo::bar::item
?总的来说,我仍然不太明白
pub use ...
的必要性。

© www.soinside.com 2019 - 2024. All rights reserved.