Challenge - 5 Problems
Vector vs Array Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateComparing Vector and Array with == operator
What is the output of this Rust code comparing a vector and an array using the == operator?
Rust
fn main() {
let v = vec![1, 2, 3];
let a = [1, 2, 3];
println!("{}", v == a);
}Attempts:
2 left
💡 Hint
Think about whether vectors and arrays can be directly compared with == in Rust.
✗ Incorrect
In Rust, vectors (Vec) and arrays ([T; N]) are different types. The == operator requires both sides to have the same type or compatible types implementing PartialEq. Vec and [T; N] do not implement PartialEq between each other, so this code will not compile.
❓ Predict Output
intermediateComparing Vector and Slice with == operator
What is the output of this Rust code comparing a vector and a slice using the == operator?
Rust
fn main() {
let v = vec![4, 5, 6];
let s: &[i32] = &[4, 5, 6];
println!("{}", v == s);
}Attempts:
2 left
💡 Hint
Recall that Vec can be compared to slices &[T] in Rust.
✗ Incorrect
Vec implements PartialEq<&[T]>, so comparing a vector and a slice with == works and compares their elements. Since both contain [4, 5, 6], the result is true.
🔧 Debug
advancedFix the code to compare Vector and Array elements
This Rust code tries to compare a vector and an array for equality but fails to compile. Which option fixes the code so it compiles and prints true?
Rust
fn main() {
let v = vec![7, 8, 9];
let a = [7, 8, 9];
println!("{}", v == a);
}Attempts:
2 left
💡 Hint
Convert the vector to a slice before comparing with the array.
✗ Incorrect
Vec can be compared to slices &[T]. The array can be coerced to a slice automatically. Using v.as_slice() converts the vector to a slice, so v.as_slice() == a compares two slices and compiles.
🧠 Conceptual
advancedWhy can't Vec and [T; N] be compared directly?
Why does Rust not allow direct comparison between Vec and [T; N] using == operator?
Attempts:
2 left
💡 Hint
Think about Rust's type system and trait implementations.
✗ Incorrect
Vec and [T; N] are distinct types. Rust only allows == if PartialEq is implemented between the two types. There is no implementation of PartialEq> for [T; N] or vice versa, so direct comparison is not allowed.
❓ Predict Output
expertOutput of comparing nested vectors and arrays
What is the output of this Rust code comparing a vector of arrays and an array of vectors?
Rust
fn main() {
let v: Vec<[i32; 2]> = vec![[1, 2], [3, 4]];
let a: [[i32; 2]; 2] = [[1, 2], [3, 4]];
println!("{}", v == a);
}Attempts:
2 left
💡 Hint
Consider the types Vec<[i32; 2]> and [[i32; 2]; 2] and whether PartialEq is implemented between them.
✗ Incorrect
Vec<[i32; 2]> and [[i32; 2]; 2] are different types. Rust does not implement PartialEq between Vec and arrays [T; N], so this comparison causes a compilation error.
