Skip to content

Latest commit

History

History
112 lines (81 loc) 路 1.67 KB

File metadata and controls

112 lines (81 loc) 路 1.67 KB

Elixir Koans - 10 Structs

import ExUnit.Assertions

Intro

defmodule Person do
  @moduledoc false
  defstruct [:name, :age]
end

Structs are defined and named after a module

person = %Person{}
assert person == ___

Unless previously defined, fields begin as nil

nobody = %Person{}
assert nobody.age == ___

You can pass initial values to structs

joe = %Person{name: "Joe", age: 23}
assert joe.name == ___

Update fields with the cons '|' operator

joe = %Person{name: "Joe", age: 23}
older = %{joe | age: joe.age + 10}
assert older.age == ___

Struct can be treated like maps

silvia = %Person{age: 22, name: "Silvia"}
assert Map.fetch(silvia, :age) == ___

Use the put_in macro to replace a nested value

defmodule Plane do
  @moduledoc false
  defstruct passengers: 0, maker: :boeing
end

defmodule Airline do
  @moduledoc false
  defstruct plane: %Plane{}, name: "Southwest"
end
airline = %Airline{}
assert put_in(airline.plane.maker, :airbus) == ___

Use the update_in macro to modify a nested value

airline = %Airline{plane: %Plane{passengers: 200}}
assert update_in(airline.plane.passengers, fn x -> x + 2 end) == ___

Use the put_in macro with atoms to replace a nested value in a non-struct

airline = %{plane: %{maker: :boeing}, name: "Southwest"}
assert put_in(airline[:plane][:maker], :cessna) == ___

Next Steps