Challenge - 5 Problems
Generic Structs Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of generic struct instantiation
What is the output of this Rust code when run?
Rust
struct Point<T> {
x: T,
y: T,
}
fn main() {
let p = Point { x: 5, y: 10 };
println!("({}, {})", p.x, p.y);
}Attempts:
2 left
💡 Hint
Look at how the struct is instantiated with integers.
✗ Incorrect
The struct Point is generic over type T. Here, T is inferred as i32 because 5 and 10 are integers. The println! macro prints the values of x and y, which are 5 and 10.
❓ Predict Output
intermediate2:00remaining
Output of generic struct with different types
What will this Rust program print?
Rust
struct Pair<T, U> {
first: T,
second: U,
}
fn main() {
let pair = Pair { first: "hello", second: 42 };
println!("{} and {}", pair.first, pair.second);
}Attempts:
2 left
💡 Hint
Check the order of fields in the struct and the println! macro.
✗ Incorrect
The struct Pair has two generic types T and U. Here, T is &str and U is i32. The println! macro prints first then second, so output is 'hello and 42'.
🔧 Debug
advanced2:00remaining
Identify the error in generic struct usage
What error does this Rust code produce when compiled?
Rust
struct Container<T> {
value: T,
}
fn main() {
let c: Container<i32> = Container { value: "text" };
}Attempts:
2 left
💡 Hint
Check the type of value assigned to the generic struct instance.
✗ Incorrect
The struct Container expects a value of type i32, but a string slice &str is assigned, causing a type mismatch error.
🧠 Conceptual
advanced2:00remaining
Understanding generic struct methods
Given this Rust code, what is the output when main runs?
Rust
struct Wrapper<T> {
item: T,
}
impl<T> Wrapper<T> {
fn new(item: T) -> Self {
Wrapper { item }
}
fn get_item(&self) -> &T {
&self.item
}
}
fn main() {
let w = Wrapper::new(3.14);
println!("{}", w.get_item());
}Attempts:
2 left
💡 Hint
Look at how the method get_item returns a reference to the item.
✗ Incorrect
The Wrapper struct holds a generic item. The method get_item returns a reference to the item. Printing it shows 3.14.
❓ Predict Output
expert3:00remaining
Output of nested generic structs
What is the output of this Rust program?
Rust
struct Outer<T> {
inner: Inner<T>,
}
struct Inner<U> {
value: U,
}
fn main() {
let o = Outer { inner: Inner { value: "Rust" } };
println!("{}", o.inner.value);
}Attempts:
2 left
💡 Hint
Focus on how the nested structs hold and access the value.
✗ Incorrect
Outer holds an Inner struct which holds a value of type &str. Printing o.inner.value prints 'Rust'.