这个问题在这里已有答案:
我有一个文件Projectile.rs在src
目录中。它目前由main.rs使用。但是,我要求FreeFall.rs文件共享在Projectile.rs中使用的相同目录。以下是目前的情况:
目录
src
|___main.rs
|___Projectile.rs
|___FreeFall.rs
main.RS
mod Projectile;
fn main() {
println!("Goed... momenteel");
Projectile::projectile(10.0, 5.0, 100.0, 7.5);
}
projectile.RS
use std;
mod FreeFall;
pub fn projectile(init: f64, AngleX: f64, AngleY: f64, AngleZ: f64) {
let mut FFAccel = FreeFall::acceleration();
struct Velocities {
x: f64,
y: f64,
z: f64,
t: f64,
};
let mut Object1 = Velocities {
x: init * AngleX.sin(),
y: init * AngleY.cos(),
z: init * AngleZ.tan(),
t: (2.0 * init.powf(-1.0) * AngleY.sin()) / FFAccel,
};
println!("{}", Object1.t);
}
free fall.RS
use std;
pub fn acceleration() {
// maths here
}
我不能只使用值9.81(这是地球上的平均重力),因为它没有考虑空气阻力,终端速度等。
我尝试将FreeFall
模块包含在main.rs中,但它没有用。
在Rust中,单文件模块不能使用mod
关键字从其他文件声明其他模块。为此,您需要为模块创建一个目录,将模块根文件命名为mod.rs
,并为每个嵌套模块在该文件中创建一个单独的文件(或目录)。
根据经验,你应该在目录的“根文件”(通常是main.rs
,lib.rs
或mod.rs
)中声明每个模块,并在其他地方声明use
。方便的是,您可以使用crate::
作为您的包的根模块,并使用它来引用您的模块。
例如:
src/
main.rs crate
foo.rs crate::foo
bar.rs crate::bar
baz/
mod.rs crate::baz
inner.rs crate::baz::inner
卖弄.人生
// declare the modules---we only do this once in our entire crate
pub mod foo;
pub mod bar;
pub mod baz;
fn main() { }
foo.人生
// use other modules in this crate
use crate::bar::*;
use crate::baz::inner::*;
巴兹/ mod.rs
// the baz module contains a nested module,
// which has to be declared here
pub mod inner;
一些资源供进一步阅读: