Modules
Organizing code with modules.
Intermediate⏱️ 40 min📚 Prerequisites: 1
Modules
Modules help organize code and make it reusable.
Module Definition
RUSTmod front_of_house { mod hosting { fn add_to_waitlist() {} fn seat_at_table() {} } mod serving { fn take_order() {} fn serve_order() {} } }
Public Modules
RUSTmod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } }
use Keyword
RUSTmod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } use crate::front_of_house::hosting; pub fn eat_at_restaurant() { hosting::add_to_waitlist(); }
Public Structs and Enums
RUSTmod back_of_house { pub struct Breakfast { pub toast: String, seasonal_fruit: String, } pub enum Appetizer { Soup, Salad, } }
use as Alias
RUSTuse std::fmt::Result; use std::io::Result as IoResult;
Code Examples
Basic Module
Module definition and usage
RUST
mod math {
pub fn add(x: i32, y: i32) -> i32 {
x + y
}
pub fn multiply(x: i32, y: i32) -> i32 {
x * y
}
}
fn main() {
let sum = math::add(5, 3);
let product = math::multiply(5, 3);
println!("Sum: {}, Product: {}", sum, product);
}Explanation:
The mod keyword defines modules. The pub keyword makes functions public. The :: syntax references modules.
use Keyword
Using use for shorthand
RUST
mod math {
pub fn add(x: i32, y: i32) -> i32 {
x + y
}
pub fn multiply(x: i32, y: i32) -> i32 {
x * y
}
}
use math::{add, multiply};
fn main() {
let sum = add(5, 3);
let product = multiply(5, 3);
println!("Sum: {}, Product: {}", sum, product);
}Explanation:
The use keyword allows us to use shortened names. This way we don't have to write the full module path every time.
Public Struct
Public struct with fields
RUST
mod back_of_house {
pub struct Breakfast {
pub toast: String,
seasonal_fruit: String,
}
impl Breakfast {
pub fn summer(toast: String) -> Breakfast {
Breakfast {
toast,
seasonal_fruit: String::from("peaches"),
}
}
}
}
use back_of_house::Breakfast;
fn main() {
let mut meal = Breakfast::summer(String::from("Rye"));
meal.toast = String::from("Wheat");
println!("Toast: {}", meal.toast);
}Explanation:
A public struct's fields are private by default. The pub keyword makes them public. This provides encapsulation.
Exercises
Creating a Module
Create a utils module with math functions!
Starter Code:
RUST
fn main() {
}