Logo

Developer learning path

Rust

Associated Data in Rust

Associated Data

36

#description

In Rust programming, Associated Data is a concept used to define a structure or container that holds data related to a specific type. Associated data can be added to an enum, struct, or trait. This data can be used to provide additional information or behavior to the type.

Enums and structs can have associated data by defining them in their declaration.

For example, if we have an enum called Shapes to represent different geometric shapes like circle, rectangle, and square, we can define associated data for each variant like this:

                    
enum Shapes {
  Circle(f32),
  Rectangle(f32, f32),
  Square(f32),
}
                  

Here, Circle has associated data of type f32 which represents its radius. Rectangle variant has two associated arguments f32 to represent the width and height respectively. Similarly, Square has an associated data of type f32 representing its side length.

We can also add associated data to a trait. In this case, the associated data is provided by the implementor of that trait.

For example, if we have a trait called Account to represent bank accounts, we can define an associated data account_balance which represents the balance of that account:

                    
trait Account {
  fn account_balance(&self) -> f32;
  const INTEREST_RATE: f32;
}
                  

Here, the account_balance associated data is a function that returns the balance of the account.

Associated data can be accessed and used in various ways within the type or outside of it depending on the use case.

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.