Skip to content

Commit

Permalink
Added pattern matching info in Remote Control Car introduction
Browse files Browse the repository at this point in the history
  • Loading branch information
Nanonej authored Jul 5, 2024
1 parent e721afd commit 9e75773
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions exercises/concept/remote-control-car/.docs/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@ 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.
```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

0 comments on commit 9e75773

Please sign in to comment.