0
0
Rustprogramming~3 mins

Why Generics with traits in Rust? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one function that magically works for many types without rewriting it?

The Scenario

Imagine you want to write a function that works with different types of data, like numbers, text, or custom objects. Without generics and traits, you'd have to write separate functions for each type, which quickly becomes messy and repetitive.

The Problem

Writing many similar functions for each data type is slow and error-prone. If you want to add a new type, you must rewrite or copy code. This wastes time and makes your program harder to maintain.

The Solution

Generics with traits let you write one flexible function that works with many types, as long as those types follow certain rules (traits). This means less code, fewer mistakes, and easier updates.

Before vs After
Before
fn print_number(n: i32) { println!("{}", n); }
fn print_text(s: &str) { println!("{}", s); }
After
fn print_item<T: std::fmt::Display>(item: T) { println!("{}", item); }
What It Enables

You can create powerful, reusable code that adapts to many data types while ensuring they behave as expected.

Real Life Example

Think of a function that sorts a list. With generics and traits, it can sort numbers, words, or even custom objects like books, as long as they can be compared.

Key Takeaways

Writing separate code for each type is slow and error-prone.

Generics with traits let you write one flexible function for many types.

This makes your code cleaner, reusable, and easier to maintain.