I have to reference this all the time :D
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 :)