DEV Community

Cover image for Understanding Rust Imports
Winston Puckett
Winston Puckett Subscriber

Posted on • Edited on

Understanding Rust Imports

I have to reference this all the time :D

Import example.rs into main.rs (same folder)

File Structure:
\src
  -example.rs
  -main.rs
Enter fullscreen mode Exit fullscreen mode

example.rs:

// example.rs
pub fn my_function() {
    println!("You called my_function!");
}
Enter fullscreen mode Exit fullscreen mode

main.rs:

// main.rs
mod example;

fn main() {
    example::my_function();
}
Enter fullscreen mode Exit fullscreen mode

Import example.rs into main.rs (example.rs in examples folder)

File Structure:
\src
  -main.rs
  \examples
    -example.rs
    -mod.rs
Enter fullscreen mode Exit fullscreen mode

examples/example.rs:

// examples/example.rs
pub fn my_function() {
    println!("You called my_function!");
}
Enter fullscreen mode Exit fullscreen mode

examples/mod.rs:

// examples/mod.rs
pub mod example;
Enter fullscreen mode Exit fullscreen mode

main.rs:

// main.rs
mod examples;

fn main() {
    examples::example::my_function();
}
Enter fullscreen mode Exit fullscreen mode

Import example1.rs into example2.rs (then call example2 from main.rs)

File Structure:
\src
  -example1.rs
  -example2.rs
  -main.rs
Enter fullscreen mode Exit fullscreen mode

example1.rs:

// example.rs
pub fn my_function() {
    println!("You called my_function!");
}
Enter fullscreen mode Exit fullscreen mode

example2.rs:

use crate::example1;

pub fn call_example_function() {
    example1::my_function();
}
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

It's really complicated. I'm not gonna try to memorize this.

Top comments (2)

Collapse
 
msfjarvis profile image
Harsh Shandilya

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 or lib.rs (depending on the type of crate). In your final example, you don't need to do pub 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).

Collapse
 
winstonpuckett profile image
Winston Puckett

Ooh. That's good to know, thank you :)