Rust, Software Development

Rust Generics With Structs, Functions, Methods, and Enums

Rust Generics is a language feature for code reuse in multiple contexts using different actual types for Structs, Functions, Methods, and Enums. Moreover, they allow for concise and clean codes by minimizing boilerplates while providing type-safety.  When we use Generics, we are using Generic Data Types in defining, for instance, a Function. Then that Function can work with different actual data types.

This post explains how they work and why they are essential.

How They Generally Work

How we use generics depends on what we are trying to define. Generally, we use any capital letter between the < and > for definition. For example, <U> is a type parameter. U represents any data type.

We can use multiple type parameters in a single definition.

Type parameters can have bounds, especially when using traits. Meaning, they are generic enough but must implement those traits. For example, <U:std::fmt::Debug>. U is any type that implements the Debug trait because we need to “debug” its contents.

Now, let’s see how we define functions, methods, structs, and enums with Generics.

Rust Generics And Struct Definitions

When using Rust Generics with Struct, place the type parameter right after the Struct name. Then, specify the field’s type using the generic type.

We can even use multiple type parameters.

Defining Enum with Rust Generics

When using Rust Generics with Enum, place the type parameter right after the Enum name and use the generic types parameters to its values.

Using the Enum is a bit different from using Structs.

Function And Method Definitions With Generic Data Types

Using Generics with Function and Method definitions differ slightly. Functions are independent blocks of codes, whereas methods are functions attached to Struct or its instance. Here is an example of Rust Generics with Struct and its method.

On the other hand, here is an example of Rust Generics with function.

These are only basic examples. There are advanced usages of Rust Generics with Structs, Functions, Methods, and Enums that are beyond the scope of this post.

Tested with Rust 1.41.0. This post is part of the Rust Programming Language For Beginners Tutorial.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like