#TIL #elixirlang atom 키를 사용해 struct를 만들거나 업데이트하고 싶다면

defmodule User do
  defstruct name: "ohyecloudy"
end

iex> unknown = struct(User, name: "unknown")
%User{name: "unknown"}

물론 생성할 때도 사용할 수 있다. keyword로 바꾸고 싶은 키와 값을 넘기면 된다.

iex> put_in(unknown.name, "ohyecloudy")
%User{name: "ohyecloudy”}

Dot-based syntax로 접근하면 얼마든지 업데이트할 수 있다.

iex> put_in(unknown, [:name], "ohyecloudy")
** (UndefinedFunctionError) function User.get_and_update/3 is undefined (User does not implement the Access behaviour)
    User.get_and_update(%User{name: "unknown"}, :name, #Function<16.9473146/1 in Kernel.put_in/3>)
    (elixir) lib/access.ex:370: Access.get_and_update/3
    (elixir) lib/kernel.ex:2114: Kernel.put_in/3

map과 다르게 struct는 Bracket-based access는 불가능하다.

iex> struct(unknown, name: "ohyecloudy")
%User{name: "ohyecloudy”}

struct/2, struct!/2 함수를 사용하면 keyword로 업데이트할 수 있다.

Feedback plz <3 @ohyecloudy, ohyecloudy@gmail.com

A Random Post