如何从同一个项目的另一个文件中包含模块?

时间:2014-10-15 17:47:51

标签: rust

通过跟随this guide我创建了一个货运项目

的src / main.rs

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

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

我使用

运行
cargo build && cargo run

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

我的项目树看起来像这样

├── src
    ├── hello.rs
    └── main.rs

和文件的内容:

的src / main.rs

use hello;

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

的src / hello.rs

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

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

modules/src/main.rs:1:5: 1:10 error: unresolved import (maybe you meant `hello::*`?)
modules/src/main.rs:1 use hello;
                                                  ^~~~~
error: aborting due to previous error
Could not compile `modules`.

我尝试按照编译器的建议并将main.rs修改为

#![feature(globs)]

extern crate hello;

use hello::*;

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

但这仍然没有多大帮助,现在我得到了这个

modules/src/main.rs:3:1: 3:20 error: can't find crate for `hello`
modules/src/main.rs:3 extern crate hello;
                                              ^~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `modules`.

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

另外,我每晚运行Rust 0.13.0并且每晚运行0.0.1。

3 个答案:

答案 0 :(得分:149)

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

要在hello.rs上添加main.rs的代码,请使用mod hello;。它会扩展到hello.rs上的代码(与之前完全一样)。您的文件结构保持不变,您的代码需要稍微更改一下:

main.rs:

mod hello;

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

hello.rs:

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

答案 1 :(得分:14)

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

./src
├── main.rs
├── other_utils
│   └── other_thing.rs
└── utils
    └── thing.rs

main.rs

#[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

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

other_utils / other_thing.rs

#[path = "../utils/thing.rs"] mod thing;

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

答案 2 :(得分:6)

您需要文件夹中的mod.rs文件。 Rust by Example更好地解释了它。

$ tree .
.
|-- my
|   |-- inaccessible.rs
|   |-- mod.rs
|   |-- nested.rs
`-- split.rs

main.rs

mod my;

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

mod.rs

pub mod nested; //if you need to include other modules

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