I'll save you some reading, it's how rust deals with importing other modules. It's entirely possible that I just don't understand how you're supposed to organize your files in rust... And that's really probably most of it, since rust is very opinionated on how programmers should program.
That being said, I went through Amethyst's Pong game tutorial and wanted to see if I could clean things up just a bit. That started a three week cycle of research into how to import and export things in Rust.
Instead of complaining, I'll just dedicate the rest of this post to different scenarios of file structures and how to import them into other files. I'll forget tomorrow, so I'll be glad this guide exists.
Import example.rs into main.rs (same folder)
File Structure:
\src
-example.rs
-main.rs
example.rs:
// example.rs
pub fn my_function() {
println!("You called my_function!");
}
main.rs:
// main.rs
mod example;
fn main() {
example::my_function();
}
Import example.rs into main.rs (example.rs in examples folder)
File Structure:
\src
-main.rs
\examples
-example.rs
-mod.rs
examples/example.rs:
// examples/example.rs
pub fn my_function() {
println!("You called my_function!");
}
examples/mod.rs:
// examples/mod.rs
pub mod example;
main.rs:
// main.rs
mod examples;
fn main() {
examples::example::my_function();
}
Import example1.rs into example2.rs (then call example2 from main.rs)
File Structure:
\src
-example1.rs
-example2.rs
-main.rs
example1.rs:
// example.rs
pub fn my_function() {
println!("You called my_function!");
}
example2.rs:
use crate::example1;
pub fn call_example_function() {
example1::my_function();
}
main.rs
// it's crazy. You have to reexport the example1 from main.rs so that example2 can see this.
pub mod example1;
mod example2;
fn main() {
example2::call_example_function();
}
Conclusion
It's really complicated. I'm not gonna try to memorize this.
Top comments (2)
It's indeed complicated but a good way to learn is to remember that as a rule of thumb, all your modules must be exported by
main.rs
orlib.rs
(depending on the type of crate). In your final example, you don't need to dopub use
,pub(crate) use
works better to export the module to the entire crate without making it public API (if you're building a library project).Ooh. That's good to know, thank you :)