首页 > 解决方案 > 在 Rust 中使用模块内部的模块

问题描述

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

自由落体

use std;

pub fn acceleration() {
    // maths here
}

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

我尝试将FreeFall模块包含到main.rs中,但它不起作用。

标签: modulerust

解决方案


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

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


例如:

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

main.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;

一些供进一步阅读的资源:


推荐阅读