Recall & Review
beginner
What is a generic function in Rust?
A generic function in Rust is a function that can work with different data types without repeating code. It uses type parameters to accept any type specified when calling the function.
Click to reveal answer
beginner
How do you declare a generic function in Rust?
You declare a generic function by adding angle brackets with a type parameter after the function name, like <T>. For example: <br>
fn example<T>(value: T) { /* code */ }Click to reveal answer
beginner
Why use generic functions instead of multiple functions for each type?
Generic functions let you write one function that works for many types, reducing repeated code and making your program easier to maintain and read.Click to reveal answer
intermediate
What is a trait bound in a generic function?
A trait bound limits the types a generic function can accept by requiring the type to implement certain behavior. For example,
fn print(value: T) means T must implement the Display trait.Click to reveal answer
intermediate
Explain the difference between
fn example<T>(value: T) and fn example(value: T).The first function accepts any type T. The second requires T to implement the Copy trait, meaning the value can be duplicated simply without moving ownership.
Click to reveal answer
What does the
<T> mean in a Rust function declaration?✗ Incorrect
The angle brackets with T declare a generic type parameter, allowing the function to accept any type.
Which of these is a correct way to restrict a generic type to types that can be printed using a where clause?
✗ Incorrect
The correct syntax to add a trait bound outside the angle brackets is using a where clause:
where T: Display.Why might you add a trait bound like
T: Copy to a generic function?✗ Incorrect
The Copy trait means the type can be copied simply, so the function can duplicate values safely.
What happens if you call a generic function with different types?
✗ Incorrect
Rust generates specialized versions of the generic function for each type it is called with.
Which keyword is used to declare a generic type parameter in Rust?
✗ Incorrect
Generic type parameters are declared inside angle brackets, like .
Explain what a generic function is and why it is useful in Rust.
Think about how one function can work with many types.
You got /3 concepts.
Describe how trait bounds work in generic functions and give an example.
Trait bounds tell Rust what behaviors a type must have.
You got /4 concepts.