1. What Are Generics?
Generics allow us to write code that works with different data types without duplicating the same logic.
For example, imagine you want to create a function that returns the larger of two numbers.
Without Generics, you might write separate functions for different types.
This creates duplicate code.
Generics help us solve this problem.
2. Generic Functions
A generic function can work with different data types.
Syntax:
Here, T is a generic type parameter. You can choose another name, but T is the common convention.
Example:
Output:
In this example, Rust infers the type of T from each function call.
3. Generic Functions with Multiple Parameters
You can use more than one generic type parameter.
Example:
Output:
Here:
Trepresents the type ofname.Urepresents the type ofage.
The two parameters do not need to have the same type.
4. Generic Functions with Return Types
Generics can also be used in return types.
Example:
Output:
The function accepts a value and returns the same type.
5. Generic Structs
Generics are not limited to functions. You can also use them with structs.
Example:
Output:
Here, Student<T> can store different types of marks.
Rust determines the type of T from the value used when creating each struct.
6. Generic Structs with Multiple Types
You can use multiple generic parameters in a struct.
Example:
Here:
Trepresents the name type.Urepresents the marks type.
7. Generic Enums
Rust also supports generic enums.
For example, consider the built-in Option<T> enum:
This is a simplified illustration of its definition.
The same enum can hold different types:
The actual standard library Option<T> also implements the standard traits needed for formatting with {:?}.
8. What Are Traits?
A trait defines a set of behaviours that a type can implement.
You can think of a trait as a contract: a type that implements the trait promises to provide its required methods.
For example, suppose different employees need to perform a common action called work().
We can define a trait for that behaviour.
Syntax:
Example:
Here, we have created a trait named Employee.
It requires implementing types to provide the work() method.
9. Implementing Traits
Use impl TraitName for TypeName to implement a trait for a type.
Example:
Output:
Explanation:
trait Employeedefines the behaviour.struct Trainercreates a type.impl Employee for Trainerimplements the trait.work()provides the required behaviour.
10. Implementing the Same Trait for Multiple Types
A trait can be implemented by multiple types.
Example:
Output:
Both types implement the same trait, but their behaviour is different.
11. Traits with Multiple Methods
A trait can contain multiple required methods.
Example:
Output:
A type implementing this trait must provide both required methods.
12. Default Methods in Traits
A trait can also provide a default implementation of a method.
The implementing type does not need to override that method.
Example:
Output:
Here, company() already has a default implementation in the trait.
13. Generic Functions with Trait Bounds
Sometimes a generic function should accept only types that support a particular behaviour.
For example, consider this function:
This will not compile for every possible type because not every type supports the Display trait.
We can use a trait bound.
Syntax:
Example:
Output:
Here, T: std::fmt::Display means that the type must implement the Display trait.
This is why println!("{}", value) works.
14. Using Multiple Trait Bounds
A generic type can be required to implement multiple traits.
Example:
Here, the generic type must implement both:
DisplayClone
The + symbol combines trait requirements.
15. The where Clause
When a function has multiple trait bounds, the declaration can become difficult to read.
Rust provides the where clause to make it cleaner.
Example using normal syntax:
Example using where:
Both examples express the same trait requirements.
16. Returning Values That Implement a Trait
Rust provides impl Trait syntax for returning a value whose concrete type implements a particular trait.
Example:
Output:
The caller knows that the returned value implements Display, but does not need to specify its concrete type.
Note: impl Trait in a return position hides one concrete return type. It does not mean the function can return completely different concrete types on different branches.
17. Understanding the derive Attribute
Rust provides commonly used traits that can be implemented automatically using #[derive(...)].
Example:
Output:
Explanation:
Trait | Purpose |
|---|---|
| Allows debug formatting using |
| Allows creating a clone using |
| Allows comparing values using |
Other commonly used derivable traits include Copy, Eq, Ord, PartialOrd, and Default.
Not every trait can be derived automatically for every type.
18. Difference Between Generics and Traits
Generics | Traits |
|---|---|
Allow code to work with different types | Define shared behaviour |
Use type parameters such as | Use the |
Help avoid duplicate code | Help define common functionality |
Can be used in functions and structs | Can be implemented by different types |
Can use trait bounds | Can be used as trait bounds |
Simple example:
Generics:
Traits:
Generics describe which types can be used. Traits describe what behaviour a type provides.