【问题标题】:Confused on how to use rust modules [duplicate]对如何使用 rust 模块感到困惑 [重复]
【发布时间】:2021-04-21 05:20:11
【问题描述】:

我有三个文件。 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.rs 中声明foo 模块
  • 实际上这有帮助,谢谢!我得到了一些有用的东西

标签: rust module


【解决方案1】:

您只需声明一次模块,在这种情况下,您将在 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();
}

【讨论】:

    猜你喜欢
    • 2015-12-24
    • 2022-01-04
    • 2015-05-16
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多