Modules
In this section we’ll give you an introduction to Rust’s module system.
Further information
Rustlings
modules1: pub
// modules1.rs // Execute `rustlings hint modules1` or use the `hint` watch subcommand for a hint. // I AM NOT DONE mod sausage_factory { // Don't let anybody outside of this module see this! fn get_secret_recipe() -> String { String::from("Ginger") } fn make_sausage() { get_secret_recipe(); println!("sausage!"); } } fn main() { sausage_factory::make_sausage(); }
Hint
add
pubEverything is private in Rust by default– but there’s a keyword we can use to make something public! The compiler error should point to the thing that needs to be public.
modules2: use self::xxx as bbb
// modules2.rs // You can bring module paths into scopes and provide new names for them with the // 'use' and 'as' keywords. Fix these 'use' statements to make the code compile. // Execute `rustlings hint modules2` or use the `hint` watch subcommand for a hint. // I AM NOT DONE mod delicious_snacks { // TODO: Fix these use statements use self::fruits::PEAR as ??? use self::veggies::CUCUMBER as ??? mod fruits { pub const PEAR: &'static str = "Pear"; pub const APPLE: &'static str = "Apple"; } mod veggies { pub const CUCUMBER: &'static str = "Cucumber"; pub const CARROT: &'static str = "Carrot"; } } fn main() { println!( "favorite snacks: {} and {}", delicious_snacks::fruit, delicious_snacks::veggie ); }
Hint
The delicious_snacks module is trying to present an external interface that is
different than its internal structure (the fruits and veggies modules and
associated constants). Complete the use statements to fit the uses in main and
find the one keyword missing for both constants.
#![allow(unused)] fn main() { pub use self::fruits::PEAR as fruit; pub use self::veggies::CUCUMBER as veggie; }
modules3
// modules3.rs // You can use the 'use' keyword to bring module paths from modules from anywhere // and especially from the Rust standard library into your scope. // Bring SystemTime and UNIX_EPOCH // from the std::time module. Bonus style points if you can do it with one line! // Execute `rustlings hint modules3` or use the `hint` watch subcommand for a hint. // I AM NOT DONE // TODO: Complete this use statement use ??? fn main() { match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()), Err(_) => panic!("SystemTime before UNIX EPOCH!"), } }