Is there a way to dynamically load/unload “mod”-ed files?

Hi, I was just wondering if there was a way to mod
A crate/src file but not load it it or unload it, and then load it back in when necessary. Also, is there a way to use crates from a vector, like

Crates: Vec<&str> = Vec::from([“some_crate”, “another_crate”]):

For I in Crates: {
Use I;
}

"Loading" of mods into the source happens at compile time, not runtime; similarly for crates. As a result, you can't either dynamically unload or load them, nor can you use them from a Vec (since you can just write out the use statements using the contents of your literal Vec, and nothing else will actually work).

use and mod are only a declaration that such thing exists, not an action performed by the program (this is very different from includes in Python or require() in JavaScript).

Thus, toggling them on and off wouldn't be any more useful to Rust programs than ability to declare that odd numbers exist or don't exist.

Dynamic loading and unloading of code is possible via dynamic libraries, but for natively-compiled languages that don't run in a virtual machine, this is a very complicated and fragile process. Overhead of having possible-to-unload code is usually much much bigger than cost of having code compiled in and firmly merged with the rest of the program.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.