module - 在 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中,但它不起作用。
解决方案
在 Rust 中,单文件模块不能使用mod
关键字从其他文件中声明其他模块。为此,您需要为模块创建一个目录,将模块命名为根文件mod.rs
,并在其中为每个嵌套模块创建一个单独的文件(或目录)。
根据经验,您应该在目录的“根文件”(通常是 或 )中声明每个模块main.rs
,lib.rs
并mod.rs
在use
其他任何地方声明。方便的是,您可以将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;
一些供进一步阅读的资源:
推荐阅读
- python - 错误:执行交叉验证时数据基数不明确
- google-apps-script - 获取多个网址的页面速度见解
- sql - 禁用某些应用程序中某些用户的更新、插入、删除
- java - 获取 Url 字符串并设置为 TextView
- mysql - 我想在满足类似条件的情况下按两个结果进行分组?
- python - 加载 ASGI 应用程序时出错。在模块“main”中找不到属性“app”
- java - 2 微服务如何维护会话和异常?
- angular - 使用 rxjs Observables 实现广度优先搜索
- java - 如果我想为 ArrayDeque 提供一个空值,我该怎么做
- typescript - 在 GraphQL Nexus.js 中定义类型时如何增加 ObjectDefinitionBlock?