0
0
Rustprogramming~30 mins

Using external crates in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Using external crates
📖 Scenario: You want to use a popular external crate called rand to generate random numbers in your Rust program. This is common when you need random values for games, simulations, or testing.
🎯 Goal: Learn how to add an external crate to your Rust project and use it to generate a random number between 1 and 10.
📋 What You'll Learn
Create a new Rust project with Cargo
Add the rand crate as a dependency in Cargo.toml
Import the rand crate in your main.rs
Generate and print a random number between 1 and 10
💡 Why This Matters
🌍 Real World
Random numbers are used in games, simulations, and testing to add unpredictability and variety.
💼 Career
Knowing how to use external crates is essential for Rust developers to reuse code and add functionality quickly.
Progress0 / 4 steps
1
Create a new Rust project
Use the command cargo new random_number in your terminal to create a new Rust project folder called random_number. Then open the main.rs file inside the src folder. Write a main function that prints "Hello, world!".
Rust
Hint

Use println!("Hello, world!"); inside the main function.

2
Add the rand crate to Cargo.toml
Open the Cargo.toml file in your project root. Add the line rand = "0.8" under the [dependencies] section to include the rand crate version 0.8.
Rust
Hint

Find the [dependencies] section in Cargo.toml and add rand = "0.8" below it.

3
Import rand and generate a random number
In main.rs, add use rand::Rng; at the top. Inside main, create a variable random_number that uses rand::thread_rng().gen_range(1..=10) to generate a random number between 1 and 10.
Rust
Hint

Import rand::Rng and use rand::thread_rng().gen_range(1..=10) to get a random number.

4
Print the random number
Add a println! statement to print the text "Random number: {random_number}" where {random_number} is the variable you created.
Rust
Hint

Use println!("Random number: {}", random_number); to show the number.