0
0
Rustprogramming~5 mins

Generic functions in Rust

Choose your learning style9 modes available
Introduction

Generic functions let you write one function that works with many types. This saves time and avoids repeating code.

When you want a function to work with different types like numbers or text.
When you want to write reusable code that handles many data types.
When you want to avoid writing the same function multiple times for different types.
Syntax
Rust
fn function_name<T>(param: T) -> T {
    // function body
}

The <T> after the function name means the function is generic over type T.

You can use T as a type inside the function for parameters and return values.

Examples
This function prints any value that can be shown as text.
Rust
fn print_value<T: std::fmt::Display>(value: T) {
    println!("Value: {}", value);
}
This function returns the same value it receives, for any type.
Rust
fn identity<T>(x: T) -> T {
    x
}
Sample Program

This program defines a generic function identity that returns what it receives. It works with both a number and a string.

Rust
fn identity<T>(x: T) -> T {
    x
}

fn main() {
    let num = identity(42);
    let text = identity("hello");

    println!("Number: {}", num);
    println!("Text: {}", text);
}
OutputSuccess
Important Notes

Generic functions can have multiple type parameters, like <T, U>.

Sometimes you need to add traits (like Display) to tell Rust what the type can do.

Summary

Generic functions let you write flexible code that works with many types.

Use <T> after the function name to make it generic.

Generic functions help avoid repeating similar code for different types.