Defining Generics in Rust
Defining Generics
53
In Rust, generics allow you to define types or functions that can work with any data type, allowing you to write more reusable and abstract code. By using generics, you can create flexible code that can work with different types in a way that is both efficient and type-safe.
To define a generic type or function, you use angle brackets (<>), followed by one or more type parameters that represent the types that the code will work with.
For example, the following code defines a generic function that takes two arguments of any type and returns a tuple containing both arguments:
fn pair<T, U>(a: T, b: U) -> (T, U) { (a, b) }
In this function, T
and U
are type parameters that represent the types of the arguments. The function then returns a tuple containing the two arguments.
When you call this function, you can specify the type parameters explicitly, like this:
let s = "hello"; let n = 42; let p = pair::<&str, i32>(s, n); // Explicitly specify type parameters assert_eq!(p, ("hello", 42));
Or you can let the compiler infer the type parameters based on the types of the arguments, like this:
let s = "world"; let n = 99; let p = pair(s, n); // Let the compiler infer the type parameters assert_eq!(p, ("world", 99));
Generics can be used in a variety of ways in Rust, such as defining generic functions, generic structs, and generic enums. By utilizing generics, you can write code that is both flexible and reusable, with less boilerplate and duplication of code.
March 27, 2023