按照本指南,我创建了一个货运项目
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/lib.rs我有以下
extern crate opal_core;
mod functions;
mod context;
mod shader;
Run Code Online (Sandbox Code Playgroud)
然后src/context.rs我有这样的东西,它试图从src/shader.rs以下方面导入符号:
use opal_core::shader::Stage;
use opal_core::shader::Shader as ShaderTrait;
use opal_core::GraphicsContext as GraphicsContextTrait;
use functions::*; // this import works fine
use shader::*; // this one doesn't
pub struct GraphicsContext {
functions: Gl
}
fn shader_stage_to_int(stage: &Stage) -> u32 {
match stage {
&Stage::Vertex => VERTEX_SHADER,
&Stage::Geometry => GEOMETRY_SHADER,
&Stage::Fragment => FRAGMENT_SHADER,
}
}
impl GraphicsContextTrait for GraphicsContext {
/// Creates a shader object
fn create_shader(&self, stage: …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的正确方法是什么?
(我是 Rust 初学者)我有三个文件:main.rs、board.rs 和 case.rs。我想将case.rs包含在board.rs中,board.rs包含在main.rs中,这样board就使用case,我们可以在main中访问board。
我已经成功地将电路板添加到主要部分,但我所做的方式似乎不适用于第二部分。
我试图将每个文件的内容封装到“mod {}”中,但它并没有改变问题。我还尝试了“mod”和“use”的每种组合。
每个文件都在文件夹 src/ 中,如果可能,我希望它们不要从那里移动。
主文件
mod board;
fn main() {
let mut b: Board = Board::new();
}
Run Code Online (Sandbox Code Playgroud)
board.rs
mod case;
pub struct Board {
board: [ Case; 9 ]
}
// There is also the impl part of course, let's keep it short
Run Code Online (Sandbox Code Playgroud)
案例.rs
pub enum Case { Empty, Full(Player) }
Run Code Online (Sandbox Code Playgroud)
将 VSCode 与 Rust 插件一起使用,board.rs 文件第一行的“case”字样带有红色下划线,它表示:
“找不到模块case
帮助的src/case.rs 文件:将文件命名为 board\case.rs 或 board\case\mod.rs 目录中的“src””
为什么不在当前目录中搜索?