0

I'm writing a game-playing AI in Rust. 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. For example, in an MVC setup, you might have

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

with a controllers/index.js file containing

////////////////////////////////////////////////////////////////////////////////
// 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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
trexinf14s
  • 261
  • 2
  • 13

1 Answers1

2

No, there is no way to import a module at runtime; Rust is a statically-compiled language.

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.

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

Rust also doesn't have "default exports" of imports, so this pattern cannot exist. You'd have to call a specifically-named function from the module.

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Then it seems like I need an index file in which I manually import each script. This setup lends itself to some annoying "gotchya"s when you're adding hundreds of scripts. Is there a better pattern? – trexinf14s Feb 19 '20 at 19:23