Structs

Elixir Structs

Defining Structs

Elixir structs define typed maps with enforced keys.

What Are Elixir Structs?

In Elixir, structs are a special kind of map with a defined set of keys. They are used to create data structures that have specific fields, providing both organization and type safety. Unlike regular maps, structs enforce the presence of specific keys and their associated types, making your code more robust and error-resistant.

Defining a Struct

Structs in Elixir are defined within a defmodule and use the defstruct keyword. You specify the keys a struct will have and optionally set default values. Below is a basic example of defining a struct:

Creating and Using Structs

Once a struct is defined, you can create instances of it using the module name as a constructor. Structs can be initialized with or without default values:

Accessing and Updating Struct Fields

You can access fields in a struct using the dot notation. To update the values, use the map update syntax. Here’s how you can do it:

Pattern Matching with Structs

Elixir structs support pattern matching as a powerful way to destructure and verify data. You can match a struct against patterns to extract data or enforce structure:

Difference Between Structs and Maps

While structs and maps are similar, there are key differences. Structs are maps with a fixed set of keys and are defined within a module, which means they can enforce key presence and types. Maps, on the other hand, are more flexible but lack this enforcement. This can lead to more runtime errors if not handled carefully.

Conclusion

Elixir structs provide a robust way to define and work with data structures, offering benefits such as enforced key presence and type safety. By using structs, you can write cleaner and more maintainable code. As you move forward, understanding the use of maps, which will be covered in the next post, will further enhance your ability to manage data in Elixir.

Structs

  • Structs
Next
Maps