Logo

Developer learning path

Rust

Generics in Rust

Generics

100

#description

Generics is a feature in Rust that allows for implementing data structures and functions that can work with different types. It provides a way to abstract over types so that code can be re-used with different data types. It is similar to templates in C++ and Java’s generics.

Let’s take an example to understand it better. Suppose you have to write a function that accepts two arguments of the same type and returns their sum. If you want to create versions of this function for all the possible data types, you’d end up writing a lot of code. But with generics, you can write a function that can be used for any data type.

Here’s the syntax for defining a generic function in Rust:

                    
fn sum<T>(x: T, y: T) -> T {
    x + y
}
                  

The “” after the function name specifies that this is a generic function. “T” is a placeholder for any type that can be used with this function. The function takes two arguments of type T and returns their sum of type T.

When calling this function, you specify the data type to be used for T.

For example, to call this function with integers, you’d write:

                    
let result = sum(5, 10);
                  

The compiler infers the type of T to be i32 (the type of the integer literals) and generates the code accordingly.

Generics can also be used with data structures.

Let’s take an example of a vector that can hold values of any data type:

                    
struct MyVector<T> {
    data: Vec<T>,
}

impl<T> MyVector<T> {
    fn push(&mut self, value: T) {
        self.data.push(value);
    }
}
                  

The “” after the struct name specifies that this is a generic data structure. The vector stores values of type T, and the push method accepts a value of type T and adds it to the vector.

Using generics, you can create highly re-usable code that can work with multiple data types without duplicating the code. Rust’s type system ensures that the code is type-safe and provides good performance.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.