Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Rust Generics


Share

Generics

Look at these two functions. They do exactly the same thing, but one works with i32 numbers and the other with f64 numbers:

Example

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

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

fn main() {
  println!("{}", bigger_i32(5, 10));
  println!("{}", bigger_f64(2.5, 1.5));
}
Try it Yourself »

Writing the same code again for every type takes time, and it is easy to make mistakes. Generics let you write the code once, and use it with many types.


Generic Functions

A generic function has a type parameter in angle brackets < > after its name. The name T (short for "type") is a placeholder for a real type, like i32 or f64:

Example

fn bigger<T: PartialOrd>(a: T, b: T) -> T {
  if a > b { a } else { b }
}

fn main() {
  println!("{}", bigger(5, 10));
  println!("{}", bigger(2.5, 1.5));
  println!("{}", bigger('a', 'z'));
}
Try it Yourself »

Rust replaces T with the right type each time you call the function: i32 for bigger(5, 10), f64 for bigger(2.5, 1.5) and char for bigger('a', 'z').


Trait Bounds

What does T: PartialOrd mean? It is a trait bound. It says that T can only be a type that implements the PartialOrd trait, which is the trait that lets values be compared with > and <. You learned about traits in the previous chapter.

Without the trait bound, Rust does not know if two T values can be compared, so the code does not compile:

Example

fn bigger<T>(a: T, b: T) -> T {
  if a > b { a } else { b } // Error
}
Try it Yourself »

The error message even suggests the fix: add PartialOrd to T.



Generic Structs

Structs can be generic too. This Point struct can store whole numbers or decimal numbers:

Example

struct Point<T> {
  x: T,
  y: T,
}

fn main() {
  let a = Point { x: 5, y: 10 };
  let b = Point { x: 1.5, y: 4.25 };

  println!("a = ({}, {})", a.x, a.y);
  println!("b = ({}, {})", b.x, b.y);
}
Try it Yourself »

Note: x and y both use the type T, so they must have the same type. Point { x: 5, y: 4.25 } gives an error, because 5 is an integer and 4.25 is a float.


Generics You Have Already Used

Vec<T> is a generic struct: Vec<i32> is a vector of integers, and Vec<&str> is a vector of string slices.

Option<T> and Result<T, E> from the Option and Error Handling chapters are generic enums.

Why Use Generics?

  • To write code once, and use it with many types
  • To avoid copying the same function for each type
  • To let the compiler check that the types are used correctly


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.