Challenge - 5 Problems
Rust Element Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Rust code accessing a vector element?
Consider the following Rust code that accesses elements in a vector. What will it print?
Rust
fn main() {
let numbers = vec![10, 20, 30, 40];
println!("{}", numbers[2]);
}Attempts:
2 left
💡 Hint
Remember that Rust vectors are zero-indexed, so the first element is at index 0.
✗ Incorrect
The vector has elements [10, 20, 30, 40]. Accessing numbers[2] gets the third element, which is 30.
❓ Predict Output
intermediateWhat happens when accessing a vector element with an invalid index?
What will happen when running this Rust code?
Rust
fn main() {
let letters = vec!['a', 'b', 'c'];
println!("{}", letters[5]);
}Attempts:
2 left
💡 Hint
Check what happens if you try to access an index outside the vector's length.
✗ Incorrect
Accessing letters[5] is invalid because the vector has only 3 elements (indices 0 to 2). Rust panics at runtime with an index out of bounds error.
❓ Predict Output
advancedWhat is the output when using get() method to access vector elements?
Analyze this Rust code and determine its output.
Rust
fn main() {
let nums = vec![1, 2, 3];
match nums.get(1) {
Some(val) => println!("{}", val),
None => println!("No value"),
}
match nums.get(5) {
Some(val) => println!("{}", val),
None => println!("No value"),
}
}Attempts:
2 left
💡 Hint
The get() method returns an Option type. If the index is valid, it returns Some(value), else None.
✗ Incorrect
nums.get(1) returns Some(2), so it prints 2. nums.get(5) returns None, so it prints 'No value'.
❓ Predict Output
advancedWhat is the output of this code accessing elements in a tuple?
What will this Rust program print?
Rust
fn main() {
let tup = (100, 200, 300);
println!("{}", tup.1);
}Attempts:
2 left
💡 Hint
Tuple elements are accessed by dot followed by the index starting at 0.
✗ Incorrect
tup.1 accesses the second element of the tuple, which is 200.
❓ Predict Output
expertWhat is the output of this Rust code accessing elements in a nested vector?
Examine the code and determine what it prints.
Rust
fn main() {
let matrix = vec![
vec![1, 2, 3],
vec![4, 5, 6],
vec![7, 8, 9],
];
println!("{}", matrix[1][2]);
}Attempts:
2 left
💡 Hint
Remember that matrix[1] accesses the second vector, then [2] accesses its third element.
✗ Incorrect
matrix[1] is vec![4,5,6], and matrix[1][2] is 6.
