Generics in Rust
Generics
100
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 “
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 “
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