0
0
Rustprogramming~5 mins

Generic structs in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Astruct Container<T> value: T;
Bstruct Container<T> { value: T }
Cstruct Container { T value }
Dstruct Container<T> (value: T);
What does this code do? <br> struct Pair { first: T, second: U }
ADefines a struct with fixed types T and U
BDefines a struct with one generic type T
CDefines a struct with two generic types T and U
DDefines a function with generic parameters
How do you create an instance of Point<f64> with x=1.0 and y=2.0?
Alet p = Point<f64>(1.0, 2.0);
Blet p: Point<f64> = Point { x: 1.0, y: 2.0 };
Clet p = Point { x: 1.0, y: 2.0 };
DBoth B and C are correct
Why are generic structs useful?
AThey allow code reuse for different data types
BThey make code slower
CThey restrict structs to one type only
DThey are only used for functions
Which of these is NOT a valid generic struct declaration?
Astruct Box { T value }
Bstruct Info<T, U> { first: T, second: U }
Cstruct Wrapper<T> (T);
Dstruct Data<T> { value: T }
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.