Challenge - 5 Problems
Rust Crate Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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);
}Attempts:
2 left
💡 Hint
Check the documentation for gen_range and how inclusive ranges are specified.
✗ Incorrect
The gen_range method accepts inclusive ranges with ..= syntax. So gen_range(1..=3) generates 1, 2, or 3 randomly.
❓ Predict Output
intermediate2: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);
}Attempts:
2 left
💡 Hint
Look at the chrono crate's DateTime methods.
✗ Incorrect
Utc::now() returns a DateTime object. The year() method returns the current year as an i32.
🔧 Debug
advanced3: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);
}Attempts:
2 left
💡 Hint
Check the JSON string syntax carefully.
✗ Incorrect
The JSON string uses double quotes inside double quotes without escaping, causing a syntax error.
📝 Syntax
advanced2: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?Attempts:
2 left
💡 Hint
Check the correct syntax for specifying versions in Cargo.toml and the correct import path.
✗ Incorrect
The version must be a string in quotes without extra symbols. The import path is regex::Regex, not regex::regex.
🚀 Application
expert3: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());
}Attempts:
2 left
💡 Hint
Cartesian product pairs every element of the first vector with every element of the second.
✗ Incorrect
3 elements in a and 2 in b produce 3*2=6 pairs.