Generics Types, Traits, and Lifetimes Flashcards
What are generics?
Abstract stand-ins for concrete types or other properties.
When defining a function that uses generics, where do we place the generic in the signature?
Where the parameter data types and return values are,
What are placed between <> in function signatures between the function name and the parameter list when using generics in a function?
Type name declarations.
What is an example of a function signature with generics?
fn largest(list: &[T]) -> T {}
What is an example of using generics in a struct definition?
struct Point {
x: T,
y: U,
}
What is an example of using generics with an enum definition?
enum Result {
Ok(T),
Err(E),
}
How does Rust avoid performance cost when using generics?
By using monomorphization.
What is monomorphization?
The process of turning generic code into specific code by filling in the concrete types that are used when compiled.
What do traits do?
Tell the Rust compiler about functionality a particular type has and can share with other types.
What are trait definitions?
A way to group method signatures together to define a set of behaviors necessary to accomplish some purpose.
What is the syntax for implementing a trait on a type?
impl for { fn foo(&self) -> { ... } }
How do you use a default trait function on a type?
Specify an empty impl block . impl for {}
Provide an example of how to define a function that accepts many different types.
pub fn notify(item: impl Summary) {
println!(“Breaking news! {}”, item.summarize());
}
What is the impl trait syntactic sugar for?
trait bounds.
Where are trait bounds placed in a function signature?
With the declaration of the generic type parameter after a colon and inside angle brackets.