0
0
Rustprogramming~20 mins

Why modules are used in Rust - See It in Action

Choose your learning style9 modes available
Understanding Why Modules Are Used in Rust
📖 Scenario: Imagine you are organizing your study notes. Instead of keeping all notes in one big pile, you separate them into folders by subject. This makes it easier to find and manage your notes.
🎯 Goal: You will create a simple Rust program that uses modules to organize functions. This will show how modules help keep code neat and easy to use.
📋 What You'll Learn
Create a module named math_utils with a function add that adds two numbers
Create a module named string_utils with a function greet that returns a greeting message
Use these modules in the main function to call add and greet
Print the results of calling these functions
💡 Why This Matters
🌍 Real World
In real software projects, modules help keep code organized and prevent confusion when many people work on the same code.
💼 Career
Understanding modules is important for writing clean, maintainable code in Rust and many other programming languages.
Progress0 / 4 steps
1
Create the math_utils module with an add function
Create a module called math_utils with a public function add that takes two i32 numbers named a and b and returns their sum.
Rust
Hint

Use mod to create a module and pub fn to make the function accessible outside the module.

2
Create the string_utils module with a greet function
Add a module called string_utils with a public function greet that takes a &str parameter named name and returns a String greeting like "Hello, {name}!".
Rust
Hint

Use format! macro to create the greeting string.

3
Use the modules in the main function
Write a main function that calls math_utils::add(5, 3) and stores the result in sum. Then call string_utils::greet("Alice") and store the result in greeting.
Rust
Hint

Use the module name followed by :: and the function name to call the function.

4
Print the results from the modules
Add println! statements in main to print "Sum: {sum}" and "Greeting: {greeting}".
Rust
Hint

Use println!("Sum: {}", sum); and println!("Greeting: {}", greeting); to show the results.