Rust
December 2, 2026 7 min read

Generics and Traits in Rust

HS
HEMANT SINGH
Technical Writer & Educator

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.

fn largest_integer(a: i32, b: i32) -> i32 {
if a > b { a } else { b }
}

fn largest_float(a: f64, b: f64) -> f64 {
if a > b { a } else { b }
}

This creates duplicate code.

Generics help us solve this problem.

2. Generic Functions

A generic function can work with different data types.

Syntax:

fn function_name<T>(value: T) {
// Function body
}

Here, T is a generic type parameter. You can choose another name, but T is the common convention.

Example:

fn display<T>(value: T) {
println!("Value: {}", value);
}

fn main() {
display(100);
display(25.5);
display("Hello Rust");
}

Output:

Value: 100
Value: 25.5
Value: Hello Rust

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:

fn display<T, U>(name: T, age: U) {
println!("Name: {}", name);
println!("Age: {}", age);
}

fn main() {
display("Hemant", 32);
}

Output:

Name: Hemant
Age: 32

Here:

  1. T represents the type of name.
  2. U represents the type of age.

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:

fn get_value<T>(value: T) -> T {
value
}

fn main() {
let number = get_value(100);
let name = get_value("Hemant");

println!("{}", number);
println!("{}", name);
}

Output:

100
Hemant

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:

struct Student<T> {
name: String,
marks: T,
}

fn main() {
let student1 = Student {
name: String::from("Hemant"),
marks: 85,
};

let student2 = Student {
name: String::from("Rahul"),
marks: 92.5,
};

println!("{} - {}", student1.name, student1.marks);
println!("{} - {}", student2.name, student2.marks);
}

Output:

Hemant - 85
Rahul - 92.5

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:

struct Student<T, U> {
name: T,
marks: U,
}

fn main() {
let student = Student {
name: "Hemant",
marks: 85,
};

println!("Name: {}", student.name);
println!("Marks: {}", student.marks);
}

Here:

  1. T represents the name type.
  2. U represents the marks type.

7. Generic Enums

Rust also supports generic enums.

For example, consider the built-in Option<T> enum:

enum Option<T> {
Some(T),
None,
}

This is a simplified illustration of its definition.

The same enum can hold different types:

fn main() {
let number: Option<i32> = Some(100);

let name: Option<String> = Some(String::from("Hemant"));

println!("{:?}", number);
println!("{:?}", name);
}

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:

trait TraitName {
fn method_name(&self);
}

Example:

trait Employee {
fn work(&self);
}

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:

trait Employee {
fn work(&self);
}

struct Trainer;

impl Employee for Trainer {
fn work(&self) {
println!("Trainer is teaching students");
}
}

fn main() {
let trainer = Trainer;

trainer.work();
}

Output:

Trainer is teaching students

Explanation:

  1. trait Employee defines the behaviour.
  2. struct Trainer creates a type.
  3. impl Employee for Trainer implements the trait.
  4. work() provides the required behaviour.

10. Implementing the Same Trait for Multiple Types

A trait can be implemented by multiple types.

Example:

trait Employee {
fn work(&self);
}

struct Trainer;
struct Receptionist;

impl Employee for Trainer {
fn work(&self) {
println!("Trainer is teaching");
}
}

impl Employee for Receptionist {
fn work(&self) {
println!("Receptionist is managing enquiries");
}
}

fn main() {
let trainer = Trainer;
let receptionist = Receptionist;

trainer.work();
receptionist.work();
}

Output:

Trainer is teaching
Receptionist is managing enquiries

Both types implement the same trait, but their behaviour is different.

11. Traits with Multiple Methods

A trait can contain multiple required methods.

Example:

trait Employee {
fn work(&self);

fn salary(&self) -> u32;
}

struct Trainer;

impl Employee for Trainer {
fn work(&self) {
println!("Trainer is teaching");
}

fn salary(&self) -> u32 {
12000
}
}

fn main() {
let trainer = Trainer;

trainer.work();

println!("Salary: {}", trainer.salary());
}

Output:

Trainer is teaching
Salary: 12000

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:

trait Employee {
fn work(&self);

fn company(&self) {
println!("Capscom Technology");
}
}

struct Trainer;

impl Employee for Trainer {
fn work(&self) {
println!("Trainer is teaching");
}
}

fn main() {
let trainer = Trainer;

trainer.work();
trainer.company();
}

Output:

Trainer is teaching
Capscom Technology

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:

fn display<T>(value: T) {
println!("{}", value);
}

This will not compile for every possible type because not every type supports the Display trait.

We can use a trait bound.

Syntax:

fn function_name<T: TraitName>(value: T) {
// Function body
}

Example:

fn display<T: std::fmt::Display>(value: T) {
println!("{}", value);
}

fn main() {
display(100);
display(25.5);
display("Hello Rust");
}

Output:

100
25.5
Hello Rust

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:

use std::fmt::Display;

fn display<T: Display + Clone>(value: T) {
let copied_value = value.clone();

println!("{}", copied_value);
}

fn main() {
display(100);
display(String::from("Rust"));
}

Here, the generic type must implement both:

  1. Display
  2. Clone

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:

use std::fmt::Display;

fn display<T: Display + Clone>(value: T) {
println!("{}", value);
}

Example using where:

use std::fmt::Display;

fn display<T>(value: T)
where
T: Display + Clone,
{
println!("{}", value);
}

fn main() {
display(100);
display(String::from("Rust"));
}

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:

fn get_message() -> impl std::fmt::Display {
String::from("Hello Rust")
}

fn main() {
let message = get_message();

println!("{}", message);
}

Output:

Hello Rust

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:

#[derive(Debug, Clone, PartialEq)]
struct Student {
name: String,
marks: i32,
}

fn main() {
let student1 = Student {
name: String::from("Hemant"),
marks: 85,
};

let student2 = student1.clone();

println!("{:?}", student1);

println!("Equal: {}", student1 == student2);
}

Output:

Student { name: "Hemant", marks: 85 }
Equal: true

Explanation:


Trait

Purpose

Debug

Allows debug formatting using {:?}

Clone

Allows creating a clone using .clone()

PartialEq

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 <T>

Use the trait keyword

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:

fn display<T>(value: T) {
// T represents a type
}

Traits:

trait Employee {
fn work(&self);
}

Generics describe which types can be used. Traits describe what behaviour a type provides.