📖 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.
Practice
(1/5)
1. What is the main purpose of using external crates in a Rust project?
easy
A. To make the code run faster automatically
B. To avoid writing any code at all
C. To add extra functionality without writing it yourself
D. To replace the Rust compiler
Solution
Step 1: Understand what external crates are
External crates are packages of code others wrote that you can use in your project.
Step 2: Identify their purpose
They help you add features without coding everything from scratch.
Final Answer:
To add extra functionality without writing it yourself -> Option C
Quick Check:
External crates = add features easily [OK]
Hint: External crates add features you don't code yourself [OK]
Common Mistakes:
Thinking crates speed up code automatically
Believing crates replace Rust compiler
Assuming crates remove all coding
2. Which of the following is the correct way to add an external crate named rand to your Rust project?
easy
A. Add import rand; in main.rs
B. Write use rand; in Cargo.toml
C. Add extern crate rand; in Cargo.toml
D. Add rand = "0.8" under [dependencies] in Cargo.toml
Solution
Step 1: Know where to add crate versions
Crate versions go under [dependencies] in Cargo.toml file.
Step 2: Identify correct syntax
The correct syntax is rand = "0.8" under [dependencies].
Final Answer:
Add rand = "0.8" under [dependencies] in Cargo.toml -> Option D
Quick Check:
Cargo.toml dependencies = rand = "0.8" [OK]
Hint: Add crate and version under [dependencies] in Cargo.toml [OK]
Common Mistakes:
Trying to use 'use' or 'import' in Cargo.toml
Writing extern crate in Cargo.toml instead of code
Adding crate info in main.rs instead of Cargo.toml
3. Given the following code and Cargo.toml setup, what will be the output?
Cargo.toml snippet:
[dependencies]
regex = "1"
main.rs snippet:
use regex::Regex;
fn main() {
let re = Regex::new(r"\d+").unwrap();
let text = "abc123def";
println!("{}", re.is_match(text));
}
medium
A. true
B. false
C. Compilation error
D. Runtime panic
Solution
Step 1: Understand what the regex checks
The regex looks for one or more digits (\d+) in the text "abc123def".
Step 2: Check if the text contains digits
The text contains "123", so the regex matches and returns true.
Final Answer:
true -> Option A
Quick Check:
Regex match found = true [OK]
Hint: Regex \d+ matches digits in string, so output true [OK]
Common Mistakes:
Thinking regex returns false if digits exist
Expecting compilation error due to crate usage
Assuming unwrap causes panic here
4. What is wrong with this Rust code using the chrono crate?
Cargo.toml:
[dependencies]
chrono = "0.4"
main.rs:
use chrono::DateTime;
fn main() {
let now = DateTime::now();
println!("{}", now);
}
medium
A. Missing extern crate chrono declaration
B. DateTime::now() does not exist; use Utc::now() instead
C. Cargo.toml version is incorrect
D. println! macro cannot print DateTime
Solution
Step 1: Check DateTime usage
DateTime::now() is not a valid method; chrono uses Utc::now() to get current time.
Step 2: Identify correct method to get current time
Use chrono::Utc::now() to get current DateTime.
Final Answer:
DateTime::now() does not exist; use Utc::now() instead -> Option B
Quick Check:
Use Utc::now() for current time [OK]
Hint: Use Utc::now(), not DateTime::now() for current time [OK]
Common Mistakes:
Trying to call DateTime::now() directly
Forgetting to import chrono::Utc
Assuming extern crate needed in 2018 edition
5. You want to use the serde_json crate to convert a Rust struct into a JSON string. Which steps are needed to do this correctly?
hard
A. Add serde and serde_json to Cargo.toml, derive Serialize on struct, then call serde_json::to_string
B. Only add serde_json to Cargo.toml and call to_string on struct directly
C. Add serde_json to Cargo.toml and use println!("{}", struct) without Serialize
D. Add serde to Cargo.toml and call struct.to_json() method
Solution
Step 1: Add required crates in Cargo.toml
You must add both serde and serde_json under [dependencies] to use serialization features.
Step 2: Derive Serialize trait on your struct
To convert struct to JSON, it must implement Serialize, usually by adding #[derive(Serialize)].
Step 3: Use serde_json::to_string to convert struct
Call serde_json::to_string(&your_struct) to get JSON string.
Final Answer:
Add serde and serde_json to Cargo.toml, derive Serialize on struct, then call serde_json::to_string -> Option A