Struct

From Elixir Wiki
Jump to navigation Jump to search

Struct[edit]

A **struct** is a composite data type that allows developers to define their own data structures with named fields. It is a fundamental concept in the Elixir programming language.

Purpose[edit]

Structs are useful for organizing and manipulating related data in a structured manner. They provide a convenient way to define and work with complex data shapes in Elixir. By defining a struct, you can ensure that the data adheres to a specific structure with predefined fields. This makes it easier to reason about the data and perform operations on it.

Syntax[edit]

To define a struct in Elixir, you use the `defstruct` keyword followed by a list of field names:

```elixir defmodule MyStruct do

 defstruct [:field1, :field2]

end ```

Here, `MyStruct` is the name of the struct, and `:field1` and `:field2` are the names of the fields.

To create an instance of the struct, you can use the `new/1` function:

```elixir my_struct = %MyStruct{} ```

You can also initialize the fields with default values:

```elixir my_struct = %MyStruct{field1: value1, field2: value2} ```

Accessing and Updating Fields[edit]

You can access the fields of a struct using the dot notation:

```elixir my_struct.field1 ```

To update the value of a field, you use the `put_in/2` function:

```elixir new_struct = put_in(my_struct.field1, new_value) ```

Pattern Matching[edit]

Structs can be used in pattern matching to destructure and extract values. This is particularly useful when working with collections of structs or when filtering data based on specific field values.

```elixir %MyStruct{field1: value} = my_struct ```

In this example, the variable `value` will be bound to the value of `field1` in `my_struct`.

Implementing Behaviours[edit]

Structs can also be used to implement behaviours in Elixir. By defining a struct that implements a specific set of fields and functions, you can ensure that certain behaviours are adhered to by any data structure that uses that struct.

Conclusion[edit]

Structs are a powerful tool in Elixir for organizing and manipulating data. They allow developers to define their own custom data structures with named fields. Structs provide a convenient way to work with complex data shapes and ensure data consistency. Whether used for organizing collections of data or implementing behaviours, structs are an essential part of the Elixir language.

See Also[edit]