Skip to content

Commit

Permalink
Rephrase; add to source doc
Browse files Browse the repository at this point in the history
  • Loading branch information
angelikatyborska committed Aug 10, 2024
1 parent 9e75773 commit c16889f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
21 changes: 21 additions & 0 deletions concepts/structs/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,27 @@ Since structs are built on maps, we can use most map functions to get and manipu
# => %Plane{engine: nil, wings: 4}
```

## Pattern matching

Structs can be used in pattern matching with or without the struct name.

```elixir
plane = %Plane{}
%Plane{wings: wings} = plane
%{wings: wings} = plane
```

By including the struct name in the pattern, you can ensure that both the left and right side are structs of the same type.

```elixir
defmodule Helicopter do
defstruct [:engine, rotors: 1]
end

%Plane{} = %Helicopter{}
# => (MatchError) no match of right hand side value: %Helicopter{engine: nil, rotors: 1}
```

## Enforcing field value initialization

We can use the `@enforce_keys` module attribute with a list of the field keys to ensure that the values are initialized when the struct is created. If a key is not listed, its value will be `nil` as seen in the above example. If an enforced key is not initialized, an error is raised.
Expand Down
13 changes: 12 additions & 1 deletion exercises/concept/remote-control-car/.docs/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,18 @@ Since structs are built on maps, we can use most map functions to get and manipu
# => %Plane{engine: nil, wings: 4}
```

Structs can also be used in pattern matching for ensuring that the matching value is a struct of the same type as the matched value.
### Pattern matching

Structs can be used in pattern matching with or without the struct name.

```elixir
plane = %Plane{}
%Plane{wings: wings} = plane
%{wings: wings} = plane
```

By including the struct name in the pattern, you can ensure that both the left and right side are structs of the same type.

```elixir
defmodule Helicopter do
defstruct [:engine, rotors: 1]
Expand Down

0 comments on commit c16889f

Please sign in to comment.