import - 有没有办法在 Rust 中导入模块,知道它的目录但不知道它的文件名?

标签 import module rust

我正在用 Rust 编写一个玩游戏的 AI。策略模块包括一个文件夹,其中包含处理特定情况的标准化模块。我希望能够在任何时候想到我想要处理的新情况时创建一个新模块。

我可以在 Node.js 中实现这一点。例如,在 MVC 设置中,您可能有

├── src
    ├── controllers
        ├── index.js
        └── ...
    ├── models
        ├── index.js
        └── ...
    └── views
        ├── index.js
        └── ...

带有一个包含的 controllers/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) ;   
  });

我可以在 Rust 中完成类似的事情吗?

最佳答案

不,没有办法在运行时导入模块; Rust 是一种静态编译的语言。

您可以做的最接近的事情是写a build script枚举您的文件系统并生成适当的mod和/或 use陈述。

require(`./${file}`)(models)


Rust 也没有导入的“默认导出”,因此这种模式不存在。您必须从模块中调用一个专门命名的函数。

也可以看看:
  • How can I statically register structures at compile time?
  • 关于import - 有没有办法在 Rust 中导入模块,知道它的目录但不知道它的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60307642/

    相关文章:

    使用 Server Management Studio 从 SQL Server Express 导入 SQL Compact 数据库

    java - Swing 和 AWT 混合不好,但还是做了,为什么?

    php - 扩展无法启用或安装的问题

    performance - 与其他系统编程语言(如 C)中通常使用的函数相比,Rust 风格的方法调用方法是否有任何开销?

    rust - 有没有办法对结构的实例执行索引访问?

    c++ - 从 DLL 动态导入 C++ 类

    node.js - ES6 和 CommonJS 导出约定的缺点

    python-3.x - "no module named torch"。但是在 Ubuntu 18.04.02 服务器版中安装了带有 conda 的 pytorch 1.3.0

    javascript - module.exports 的 nodejs 缓存问题

    rust - 如何使固定大小的数组保持未初始化状态?