关于rust:如何包含同一项目中另一个文件中的模块?

How to include a module from another file from the same project?

按照本指南,我创建了一个货运项目。

src/main.rs

1
2
3
4
5
6
7
8
9
fn main() {
    hello::print_hello();
}

mod hello {
    pub fn print_hello() {
        println!("Hello, world!");
    }
}

我运行使用

1
cargo build && cargo run

并且它编译没有错误。 现在,我试图将主模块一分为二,但无法弄清楚如何从另一个文件中包含一个模块。

我的项目树看起来像这样

1
2
3
├── src
  ├── hello.rs
  └── main.rs

以及文件的内容:

src/main.rs

1
2
3
4
5
use hello;

fn main() {
    hello::print_hello();
}

src/hello.rs

1
2
3
4
5
mod hello {
    pub fn print_hello() {
        println!("Hello, world!");
    }
}

当我用cargo build编译时,我得到

1
2
3
4
5
error[E0432]: unresolved import `hello`
 --> src/main.rs:1:5
  |
1 | use hello;
  |     ^^^^^ no `hello` external crate

我尝试遵循编译器的建议并将main.rs修改为:

1
2
3
4
5
6
7
8
9
#![feature(globs)]

extern crate hello;

use hello::*;

fn main() {
    hello::print_hello();
}

但这仍然无济于事,现在我明白了:

1
2
3
4
5
error[E0463]: can't find crate for `hello`
 --> src/main.rs:3:1
  |
3 | extern crate hello;
  | ^^^^^^^^^^^^^^^^^^^ can't find crate

是否有一个简单的示例,说明如何将当前项目中的一个模块包含到项目的主文件中?


您不需要hello.rs文件中的mod hello。除板条根(可执行文件为main.rs,库为lib.rs)以外的任何文件中的代码都自动在模块中命名。

要将hello.rs中的代码包含在main.rs中,请使用mod hello;。它被扩展为hello.rs中的代码(与您之前完全一样)。您的文件结构保持不变,并且您的代码需要稍作更改:

main.rs

1
2
3
4
5
mod hello;

fn main() {
    hello::print_hello();
}

hello.rs

1
2
3
pub fn print_hello() {
    println!("Hello, world!");
}


如果您希望使用嵌套模块...

锈2018

不再需要文件mod.rs(尽管仍受支持)。惯用的替代方法是将文件命名为模块名称:

1
2
3
4
5
6
7
$ tree src
src
├── main.rs
├── my
│ ├── inaccessible.rs
│ └── nested.rs
└── my.rs

main.rs

1
2
3
4
5
mod my;

fn main() {
    my::function();
}

my.rs

1
2
3
4
5
pub mod nested; // if you need to include other modules

pub fn function() {
    println!("called `my::function()`");
}

锈2015

您需要将mod.rs文件放入与模块名称相同的文件夹中。举例来说,Rust解释得更好。

1
2
3
4
5
6
7
$ tree src
src
├── main.rs
└── my
    ├── inaccessible.rs
    ├── mod.rs
    └── nested.rs

main.rs

1
2
3
4
5
mod my;

fn main() {
    my::function();
}

mod.rs

1
2
3
4
5
pub mod nested; // if you need to include other modules

pub fn function() {
    println!("called `my::function()`");
}


我真的很喜欢园丁的回应。我一直在对模块声明使用建议。如果与此相关的技术问题,请有人提出。

1
2
3
4
5
6
./src
├── main.rs
├── other_utils
│   └── other_thing.rs
└── utils
    └── thing.rs

1
2
3
4
5
6
7
#[path ="utils/thing.rs"] mod thing;
#[path ="other_utils/other_thing.rs"] mod other_thing;

fn main() {
  thing::foo();
  other_thing::bar();
}

utils / thing.rs

1
2
3
pub fn foo() {
  println!("foo");
}

other_utils / other_thing.rs

1
2
3
4
5
6
#[path ="../utils/thing.rs"] mod thing;

pub fn bar() {
  println!("bar");
  thing::foo();
}