0
0
Rustprogramming~20 mins

Generic structs in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Generic Structs Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
}
A(5, 10)
B(x, y)
C(0, 0)
DCompilation error
Attempts:
2 left
💡 Hint
Look at how the struct is instantiated with integers.
Predict Output
intermediate
2: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);
}
A42 and hello
Bhello and hello
CCompilation error due to mismatched types
Dhello and 42
Attempts:
2 left
💡 Hint
Check the order of fields in the struct and the println! macro.
🔧 Debug
advanced
2: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" };
}
ANo error, compiles successfully
BType mismatch error: expected i32 but found &str
CSyntax error: missing semicolon
DMissing lifetime specifier error
Attempts:
2 left
💡 Hint
Check the type of value assigned to the generic struct instance.
🧠 Conceptual
advanced
2: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());
}
ACompilation error: missing trait bound
BWrapper { item: 3.14 }
C3.14
DRuntime error
Attempts:
2 left
💡 Hint
Look at how the method get_item returns a reference to the item.
Predict Output
expert
3: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);
}
ARust
BOuter { inner: Inner { value: "Rust" } }
CCompilation error: cannot infer type
DRuntime panic
Attempts:
2 left
💡 Hint
Focus on how the nested structs hold and access the value.