0
0
Rustprogramming~3 mins

Why Generic functions 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 extra effort?

The Scenario

Imagine you want to write a function that adds two numbers. You write one for integers, then another for floating-point numbers, and maybe another for some custom types. This quickly becomes a mess of repeated code.

The Problem

Writing separate functions for each type is slow and error-prone. If you want to change the logic, you must update every version. It's like copying and pasting the same recipe with tiny changes--easy to make mistakes and hard to maintain.

The Solution

Generic functions let you write one function that works with many types. You write the logic once, and Rust fills in the details for each type automatically. This keeps your code clean, safe, and easy to update.

Before vs After
Before
fn add_i32(a: i32, b: i32) -> i32 { a + b }
fn add_f64(a: f64, b: f64) -> f64 { a + b }
After
fn add<T: std::ops::Add<Output = T>>(a: T, b: T) -> T { a + b }
What It Enables

Generic functions unlock flexible, reusable code that adapts to many types without rewriting.

Real Life Example

Think of a calculator app that can add integers, decimals, or even complex numbers--all using the same add function behind the scenes.

Key Takeaways

Manual duplication leads to messy, hard-to-maintain code.

Generic functions let you write one function for many types.

This makes your code cleaner, safer, and easier to update.