Access Behaviour on Structs

I ended up here from trying to ask a new question: Where can one find details on the reasoning behind why Structs in Elixir do not implement the Access behaviour?

As a first, rookie take on this, I started with something like

  # `Struct`s don't implement the `Access` behaviour.
  #
  # TODO: Similar patterns exist throughout the codebase. Re-evaluate if
  #       `get_in_struct/2` and `put_in_struct/3` are the desired approach.
  #
  # Allow for something similar to `put_in` for `Struct`.
  @spec put_in_struct(struct(), nonempty_list(atom()), term()) :: struct()
  defp put_in_struct(struct, location, value) do
    locator = Enum.map(location, &Access.key/1)
    put_in(struct, locator, value)
  end

  # Allow for something similar to `get_in` for `Struct`.
  @spec get_in_struct(struct(), nonempty_list(atom())) :: term()
  defp get_in_struct(struct, location) do
    locator = Enum.map(location, &Access.key/1)
    get_in(struct, locator)
  end

Digging deeper, my current understanding is that this approach is not Elixir-idiomatic. Instead, it is the Access behaviour that “should” be implemented.

Is this understanding aligned with the Elixir community’s best practices?

If so, since this link is out of date*, where can one find an example of implementing the Access behaviour for Structs?

1 Like