module - 在 Rust 中的模块内部使用模块

标签 module rust

<分区>

我在 src 目录中有一个文件 Projectile.rs。它目前由 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);
}

FREEFALL.RS

use std;

pub fn acceleration() {
    // maths here
}

我不能只使用值 9.81(这是地球上的平均重力),因为它没有考虑空气阻力、终端速度等。

我尝试将 FreeFall 模块包含到 main.rs 中,但没有成功。

最佳答案

在 Rust 中,单文件模块不能使用 mod 关键字从其他文件声明其他模块。为此,您需要为模块创建一个目录,将模块根文件命名为 mod.rs,并在其中为每个嵌套模块创建一个单独的文件(或目录)。

根据经验,您应该在“根文件”中声明每个模块(通常是 main.rslib.rsmod.rs ) 的目录,并在其他任何地方使用。方便的是,您可以使用 crate:: 作为您的 crate 的根模块,并使用它来引用您的模块。


例如:

src/
  main.rs             crate
  foo.rs              crate::foo
  bar.rs              crate::bar
  baz/
    mod.rs            crate::baz
    inner.rs          crate::baz::inner

ma​​in.rs

// declare the modules---we only do this once in our entire crate
pub mod foo;
pub mod bar;
pub mod baz;

fn main() { }

foo.rs

// use other modules in this crate
use crate::bar::*;
use crate::baz::inner::*;

baz/mod.rs

// the baz module contains a nested module,
// which has to be declared here
pub mod inner;

进一步阅读的一些资源:

关于module - 在 Rust 中的模块内部使用模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55171692/

相关文章:

rust - 如何在Rust中将借来的值保存到struct字段中

module - xcrun swift 在命令行上生成 <unknown> :0: error: could not load shared library

javascript - 在 node.js 中获取模块的名称

rust - 如何借用结构的 curry 函数字段?

rust - 操作返回 Box<Future> 时的生命周期编译器错误

rust - 基于特征标志有条件地推导

python - 导入错误 : No module named downsample

perl - 为什么我不能简单地将已安装的 Perl 模块复制到其他机器上?

vb.net - 在 VB.NET 中直接调用模块函数是一种好习惯吗?

vector - 同时可变访问保证不相交的大向量的任意索引