How to include a module from another file from the same project?
按照本指南,我创建了一个货运项目。
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 |
以及文件的内容:
1 2 3 4 5 | use hello; fn main() { hello::print_hello(); } |
1 2 3 4 5 | mod hello { pub fn print_hello() { println!("Hello, world!"); } } |
当我用
1 2 3 4 5 | error[E0432]: unresolved import `hello` --> src/main.rs:1:5 | 1 | use hello; | ^^^^^ no `hello` external crate |
我尝试遵循编译器的建议并将
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 |
是否有一个简单的示例,说明如何将当前项目中的一个模块包含到项目的主文件中?
您不需要
要将
1 2 3 4 5 | mod hello; fn main() { hello::print_hello(); } |
1 2 3 | pub fn print_hello() { println!("Hello, world!"); } |
如果您希望使用嵌套模块...
锈2018
不再需要文件
1 2 3 4 5 6 7 | $ tree src src ├── main.rs ├── my │ ├── inaccessible.rs │ └── nested.rs └── my.rs |
1 2 3 4 5 | mod my; fn main() { my::function(); } |
1 2 3 4 5 | pub mod nested; // if you need to include other modules pub fn function() { println!("called `my::function()`"); } |
锈2015
您需要将
1 2 3 4 5 6 7 | $ tree src src ├── main.rs └── my ├── inaccessible.rs ├── mod.rs └── nested.rs |
1 2 3 4 5 | mod my; fn main() { my::function(); } |
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(); } |