按照本指南,我创建了一个货运项目
SRC/main.rs
fn main() {
hello::print_hello();
}
mod hello {
pub fn print_hello() {
println!("Hello, world!");
}
}
Run Code Online (Sandbox Code Playgroud)
我运行使用
cargo build && cargo run
Run Code Online (Sandbox Code Playgroud)
它编译没有错误.现在我正在尝试将主模块分成两部分,但无法弄清楚如何从另一个文件中包含一个模块.
我的项目树看起来像这样
??? src
??? hello.rs
??? main.rs
Run Code Online (Sandbox Code Playgroud)
和文件的内容:
SRC/main.rs
use hello;
fn main() {
hello::print_hello();
}
Run Code Online (Sandbox Code Playgroud)
SRC/hello.rs
mod hello {
pub fn print_hello() {
println!("Hello, world!");
}
}
Run Code Online (Sandbox Code Playgroud)
当我编译它src/main.rs,我得到
error[E0432]: unresolved import `hello`
--> src/main.rs:1:5
|
1 | use hello;
| ^^^^^ no `hello` external crate
Run Code Online (Sandbox Code Playgroud)
我试图遵循编译器的建议并修改main.rs
#![feature(globs)]
extern crate hello; …Run Code Online (Sandbox Code Playgroud) 如果您有这样的目录结构:
src/main.rs
src/module1/blah.rs
src/module1/blah2.rs
src/utils/logging.rs
Run Code Online (Sandbox Code Playgroud)
你如何使用其他文件中的函数?
从Rust教程,听起来我应该能够做到这一点:
main.rs
mod utils { pub mod logging; }
mod module1 { pub mod blah; }
fn main() {
utils::logging::trace("Logging works");
module1::blah::doit();
}
Run Code Online (Sandbox Code Playgroud)
logging.rs
pub fn trace(msg: &str) {
println!(": {}\n", msg);
}
Run Code Online (Sandbox Code Playgroud)
blah.rs
mod blah2;
pub fn doit() {
blah2::doit();
}
Run Code Online (Sandbox Code Playgroud)
blah2.rs
mod utils { pub mod logging; }
pub fn doit() {
utils::logging::trace("Blah2 invoked");
}
Run Code Online (Sandbox Code Playgroud)
但是,这会产生错误:
error[E0583]: file not found for module `logging`
--> src/main.rs:1:21
|
1 | mod utils { pub …Run Code Online (Sandbox Code Playgroud) 有很多关于使用模块的Rust 文档,但我还没有找到一个包含多个模块的Cargo二进制文件的示例,其中一个模块使用另一个模块.我的例子在src文件夹中有三个文件.模块a和b处于同一级别.一个不是另一个的子模块.
main.rs:
mod a;
fn main() {
println!("Hello, world!");
a::a();
}
Run Code Online (Sandbox Code Playgroud)
a.rs:
pub fn a() {
println!("A");
b::b();
}
Run Code Online (Sandbox Code Playgroud)
和b.rs:
pub fn b() {
println!("B");
}
Run Code Online (Sandbox Code Playgroud)
我试过的变化use b和mod b内部a.rs,但我不能得到这个代码进行编译.use b例如,如果我尝试使用,则会收到以下错误:
--> src/a.rs:1:5
|
1 | use b;
| ^ no `b` in the root. Did you mean to use `a`?
Run Code Online (Sandbox Code Playgroud)
让Rust认识到我想在货物应用程序中使用模块a中的模块b的正确方法是什么?
我正在使用rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14),我有以下设置:
my_app/
|
|- my_lib/
| |
| |- foo
| | |- mod.rs
| | |- a.rs
| | |- b.rs
| |
| |- lib.rs
| |- Cargo.toml
|
|- src/
| |- main.rs
|
|- Cargo.toml
Run Code Online (Sandbox Code Playgroud)
SRC/main.rs:
extern crate my_lib;
fn main() {
my_lib::some_function();
}
Run Code Online (Sandbox Code Playgroud)
my_lib/lib.rs:
pub mod foo;
fn some_function() {
foo::do_something();
}
Run Code Online (Sandbox Code Playgroud)
my_lib /富/ mod.rs:
pub mod a;
pub mod b;
pub fn do_something() {
b::world();
}
Run Code Online (Sandbox Code Playgroud)
my_lib …