[英]Is there a way to import a module in Rust knowing its directory but not its filename?
I'm writing a game-playing AI in Rust.我正在用 Rust 编写一个玩游戏的 AI。 The strategy module includes a folder with standardized modules that handle specific situations.
策略模块包括一个文件夹,其中包含处理特定情况的标准化模块。 I want to be able to create a new module anytime I think of a new situation that I would like handled.
我希望能够在任何时候想到我想要处理的新情况时创建一个新模块。
I can accomplish this in Node.我可以在 Node.js 中完成此操作。 For example, in an MVC setup, you might have
例如,在 MVC 设置中,您可能有
├── src
├── controllers
├── index.js
└── ...
├── models
├── index.js
└── ...
└── views
├── index.js
└── ...
with a controllers/index.js file containing带有一个包含控制器/index.js 的文件
////////////////////////////////////////////////////////////////////////////////
// Imports
////////////////////////////////////////////////////////////////////////////////
// Models
const models = require('../models');
// Modules
const fs = require('fs');
const path = require('path');
////////////////////////////////////////////////////////////////////////////////
// Module
////////////////////////////////////////////////////////////////////////////////
const controllers = {};
const basename = path.basename(__filename);
fs.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) &&
(file !== basename) &&
(file.slice(-3) === '.js');
})
.forEach(file => {
controllers[file.slice(0,-3)] = require(`./${file}`)(models) ;
});
Can I accomplish something similar in Rust?我可以在 Rust 中完成类似的事情吗?
No, there is no way to import a module at runtime;不,无法在运行时导入模块; Rust is a statically-compiled language.
Rust 是一种静态编译语言。
The closest thing you could do would be to write a build script that enumerates your filesystem and generates the appropriate mod
and/or use
statements.您可以做的最接近的事情是编写一个构建脚本来枚举您的文件系统并生成适当的
mod
和/或use
语句。
require(`./${file}`)(models)
Rust also doesn't have "default exports" of imports, so this pattern cannot exist. Rust 也没有导入的“默认导出”,因此这种模式不存在。 You'd have to call a specifically-named function from the module.
您必须从模块中调用特定命名的函数。
See also:也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.