Recall & Review
beginner
What is a generic struct in Rust?
A generic struct in Rust is a struct that can hold data of any type, specified when the struct is used. It uses type parameters to be flexible and reusable.
Click to reveal answer
beginner
How do you define a generic struct with one type parameter in Rust?
You add angle brackets with a type parameter after the struct name, like <T>. For example: <br>
struct Point<T> {
x: T,
y: T,
}Click to reveal answer
intermediate
Can a generic struct have multiple type parameters? How?
Yes. You list multiple type parameters separated by commas inside the angle brackets. For example: <br>
struct Pair {
first: T,
second: U,
}Click to reveal answer
beginner
How do you create an instance of a generic struct with a specific type?
You specify the type when creating the instance or let Rust infer it. For example: <br><pre>let p = Point { x: 5, y: 10 }; // Rust infers T = i32
let p2: Point<f64> = Point { x: 1.0, y: 4.0 };</pre>Click to reveal answer
beginner
Why use generic structs instead of fixed-type structs?
Generic structs let you write flexible and reusable code. You can use the same struct for different data types without rewriting it for each type.Click to reveal answer
How do you declare a generic struct named Container with one type parameter T?
✗ Incorrect
The correct syntax uses angle brackets after the struct name to declare the type parameter T.
What does this code do? <br> struct Pair { first: T, second: U }
✗ Incorrect
The struct Pair has two generic type parameters T and U, allowing it to hold two values of possibly different types.
How do you create an instance of Point<f64> with x=1.0 and y=2.0?
✗ Incorrect
Rust can infer the type from the values or you can specify it explicitly.
Why are generic structs useful?
✗ Incorrect
Generic structs let you write one struct that works with many types, improving code reuse.
Which of these is NOT a valid generic struct declaration?
✗ Incorrect
Option A is invalid because it does not declare T as a generic parameter properly.
Explain what a generic struct is and how you define one in Rust.
Think about how you make a struct work with any type.
You got /3 concepts.
Describe how to create and use an instance of a generic struct with multiple type parameters.
Remember to specify types or let Rust infer them.
You got /3 concepts.