Learn about Generics in Rust

Tram Ho

1. Introduction

With Rust, generics is a concept born to avoid code duplication when dealing with a logic for many different data types. It still sounds a bit vague. We’ll go into more detail soon.

The example below is quite easy to understand, we will find the largest value in an array of integers.

In the second example, we find the maximum value of two arrays and print them. The code still runs correctly but the loop logic to find the maximum value is repeated, looking very cumbersome.

In the third example, we’ll move the max value logic into a separate function and call it back when necessary.

Through the above 3 examples, the code has gradually become more compact and optimized through the following steps:

  1. Identify duplicate code
  2. Put duplicate codes into a separate function and specify input parameters and return values.
  3. Replace the duplicate logic with a function call.

What if the largest function we use is not only for data type i32 but also other data types such as char, float, … We will write more functions with input parameters of data types to be processed. . But it seems that the code logic is duplicated a lot This is when we need to use generics

2. Generic Data Types

Generic with function

In the example below, we want to find the largest character in an array of characters. Although the logic is the same as how to find the largest value in an array of integers, the input value in the largest_32 function before must be of type i32 . We had to create a new function, largest_char . It’s time we use generics to optimize our code!

The syntax when using generics to define the largest function will be as follows:

T is a generic definition parameter for the data type to which the largest function is passed. T stands for type , we can use other characters like U, A, B, C, Y, Z … , but usually the default choice is conventionally T.

When using the T parameter ta, it should be declared immediately after the function name by including a <> so that the compiler understands that you are using generics with the parameter T .

The largest function after using generics will look like this:

Generic with struct

We can also use generics with structs, let’s take a look at the following examples:

Generic with enum

Generic with methods

We can use generics for implementing methods of struct or enum.

Note that we must declare T right after impl to be able to use T on Point <T> type and not always the generic parameter type defined in the struct will be the same as in the method of the struct.

Additional note : Using generics does not affect program performance compared to using specific data types.

References

Rust Programming Language

Share the news now

Source : Viblo