about
04/28/2022
RustBites - Generics and Traits
Rust Bite - Generics and Traits
generic types, traits, exercises
1. Generics:
2. Traits:
- Traits may define methods they declare, but usually don't.
- The &self and &mut self arguments are used for any methods bound to a struct.
- The return type Self requires the clone method to return an instance of its own type.
Frequently Used Standard Traits:
Trait | Description |
---|---|
Copy | Copy is a marker trait, so it has no methods for application code to call. It's used by compiler to decide how to handle bindings and assignments. If the data is Copy its value is copied from source to destination. |
Clone |
Clone creates a new instance of the cloner type and copies into it the cloner's resources.
This is an expensive operation so Rust makes that explicit with the |
Debug |
Debug enables functions and structs to use the Debug format specifier " |
Display |
Display provides custom formatting for user-defined functions and structs with the
" |
Default |
Default requires implementors to supply the associated function |
ToString |
ToString requires the method: |
From and Into |
From requires the method: |
FromStr |
FromStr requires the function |
AsRef |
AsRef requires the function: |
Deref |
Deref specifies the function: |
Sized and ?Sized | Sized is a marker trait for types with constant size known at compile time. The ?Sized trait means that the type size is not known at compile time, e.g., a heap-based array. |
Read |
Read specifies function:
|
Write |
Write specifies the function:
|
Iterator |
Iterator specifies the function: |
IntoIterator |
IntoIterator specifies the function: |
3. Exercises:
- Write a generic function that accepts an array, [N; T] and converts that to a Vec<T>. Do that directly, without using any additional help from the Rust libraries.
- Repeat exercise #1 using an iterator to do all the work. Write the shortest line of code you can to accomplish this.
- Create a struct that holds the fields: name, occupation, and age (you pick the types). Now, can you endow that with the Display trait?
- Write code to demonstrate all the ways you can think of to convert a literal string: "a string" into a String instance.