rust - 对如何使用 rust 模块感到困惑

标签 rust module

这个问题在这里已经有了答案:





Split a module across several files

(6 个回答)



How can I include a module from another file from the same project?

(5 个回答)



How to use one module from another module in a Rust cargo project?

(2 个回答)


去年关闭。




我有三个文件。 main.rs、foo.rs、bar.rs 都在 src 目录下。我想在 bar.rs 中使用 foo.rs 中的内容。所以我有 mod foo;酒吧内。但我得到一个错误,如下所示。我不想将 foo.rs 放在子目录中,例如src/bar/foo.rs 还有另一种构造代码的方法吗?因为我希望 foo.rs 可以在除 bar.rs 之外的许多不同的地方使用。或者,如果你能告诉我你如何构建一个包含多个文件的大项目,那就足够了。

    file not found for module `foo`
     --> src/bar.rs:1:1
      |
    1 | mod foo;
      | ^^^^^^^^
      |
      = help: to create the module `foo`, create file "src/bar/foo.rs"

    error: aborting due to previous error
main.rs
mod bar;

fn main() {
    println!("Hello, world!");
}
foo.rs
pub fn do_something() {
    
}
bar.rs
mod foo;

最佳答案

您只需声明一次模块,在这种情况下,您将在 main 中声明这两个模块。然后您就可以使用 use crate::{mod_name} 从代码库中的任何其他位置导入它们.例子:src/main.rs

// declare foo & bar modules
mod foo;
mod bar;

fn main() {
    foo::foo();
    foo::call_bar();
    bar::bar();
    bar::call_foo();
}
src/foo.rs
// import bar module
use crate::bar;

pub fn foo() {
    println!("foo");
}

pub fn call_bar() {
    bar::bar();
}
src/bar.rs
// import foo module
use crate::foo;

pub fn bar() {
    println!("bar");
}

pub fn call_foo() {
    foo::foo();
}

关于rust - 对如何使用 rust 模块感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65748628/

相关文章:

rust - 静态的 future 生命周期不长

macros - 如何将文件的内容作为参数包含在宏中?

function - Rust 仅在拆分为多个语句时才编译方法链

python - 如何从自定义模块在 Odoo 中创建库存变动?

swift - Interface Builder 中自定义类的模块不正确

rust - 为什么链接生存期仅与可变引用有关?

rust - 如何创建一个全局的、可变的单例?

ruby - 执行包含多个模块的同名方法

python - 使用 django 模板时出错

找不到 Python pip 安装模块。如何将python链接到pip位置?