Bird
Raised Fist0
Rustprogramming~20 mins

Using external crates in Rust - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rust Crate Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Rust code using the rand crate?
Consider this Rust program that uses the rand crate to generate a random number between 1 and 3 inclusive. What will it print?
Rust
use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    let n = rng.gen_range(1..=3);
    println!("{}", n);
}
APrints a random number: 0, 1, or 2
BRuntime panic due to invalid range
CCompilation error: gen_range requires exclusive upper bound
DPrints a random number: 1, 2, or 3
Attempts:
2 left
💡 Hint
Check the documentation for gen_range and how inclusive ranges are specified.
❓ Predict Output
intermediate
2:00remaining
What does this code print using the chrono crate?
This Rust program uses the chrono crate to get the current year. What is the output?
Rust
use chrono::Utc;
use chrono::Datelike;

fn main() {
    let year = Utc::now().year();
    println!("{}", year);
}
APrints the current year as a 4-digit number, e.g., 2024
BCompilation error: missing trait import for year()
CPrints the current month number
DRuntime error: Utc::now() returns a string, not a DateTime
Attempts:
2 left
💡 Hint
Look at the chrono crate's DateTime methods.
🔧 Debug
advanced
3:00remaining
Why does this code fail to compile when using the serde_json crate?
This Rust code tries to parse a JSON string into a struct using serde_json but fails. What is the cause?
Rust
use serde::Deserialize;

#[derive(Deserialize)]
struct Person {
    name: String,
    age: u8,
}

fn main() {
    let data = "{\"name\": \"Alice\", \"age\": 30}";
    let p: Person = serde_json::from_str(data).unwrap();
    println!("{} is {} years old", p.name, p.age);
}
APerson struct missing Debug trait for unwrap()
BMissing serde_json crate in Cargo.toml
CSyntax error in JSON string due to unescaped quotes
DAge field type mismatch: u8 cannot hold 30
Attempts:
2 left
💡 Hint
Check the JSON string syntax carefully.
📝 Syntax
advanced
2:00remaining
Which option correctly adds the external crate in Cargo.toml and imports it in Rust?
You want to use the regex crate in your Rust project. Which option correctly shows the Cargo.toml dependency and the import statement?
A
[dependencies]
regex = 1

use regex::Regex;
B
[dependencies]
regex = "1"

use regex::Regex;
C
[dependencies]
regex = "^1.0"

use regex::Regex;
D
[dependencies]
regex = "=1.0"

use regex::regex;
Attempts:
2 left
💡 Hint
Check the correct syntax for specifying versions in Cargo.toml and the correct import path.
🚀 Application
expert
3:00remaining
How many items does this code produce using itertools crate?
This Rust code uses the itertools crate to create a Cartesian product of two vectors. How many pairs are printed?
Rust
use itertools::iproduct;

fn main() {
    let a = vec![1, 2, 3];
    let b = vec![4, 5];
    let pairs: Vec<_> = iproduct!(a.iter(), b.iter()).collect();
    println!("{}", pairs.len());
}
A6
B5
C3
D2
Attempts:
2 left
💡 Hint
Cartesian product pairs every element of the first vector with every element of the second.

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

  1. Step 1: Understand what external crates are

    External crates are packages of code others wrote that you can use in your project.
  2. Step 2: Identify their purpose

    They help you add features without coding everything from scratch.
  3. Final Answer:

    To add extra functionality without writing it yourself -> Option C
  4. 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

  1. Step 1: Know where to add crate versions

    Crate versions go under [dependencies] in Cargo.toml file.
  2. Step 2: Identify correct syntax

    The correct syntax is rand = "0.8" under [dependencies].
  3. Final Answer:

    Add rand = "0.8" under [dependencies] in Cargo.toml -> Option D
  4. 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

  1. Step 1: Understand what the regex checks

    The regex looks for one or more digits (\d+) in the text "abc123def".
  2. Step 2: Check if the text contains digits

    The text contains "123", so the regex matches and returns true.
  3. Final Answer:

    true -> Option A
  4. 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

  1. Step 1: Check DateTime usage

    DateTime::now() is not a valid method; chrono uses Utc::now() to get current time.
  2. Step 2: Identify correct method to get current time

    Use chrono::Utc::now() to get current DateTime.
  3. Final Answer:

    DateTime::now() does not exist; use Utc::now() instead -> Option B
  4. 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

  1. Step 1: Add required crates in Cargo.toml

    You must add both serde and serde_json under [dependencies] to use serialization features.
  2. Step 2: Derive Serialize trait on your struct

    To convert struct to JSON, it must implement Serialize, usually by adding #[derive(Serialize)].
  3. Step 3: Use serde_json::to_string to convert struct

    Call serde_json::to_string(&your_struct) to get JSON string.
  4. Final Answer:

    Add serde and serde_json to Cargo.toml, derive Serialize on struct, then call serde_json::to_string -> Option A
  5. Quick Check:

    Serialize + serde_json::to_string = JSON string [OK]
Hint: Add serde + serde_json, derive Serialize, then use to_string [OK]
Common Mistakes:
  • Forgetting to add serde crate
  • Not deriving Serialize on struct
  • Trying to call to_string directly on struct
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard