Keyword.fetch vs bracket access []

Hi everyone,

I’m currently going through the Getting Started and I have encountered the following:

defmodule KV.Registry do
  use GenServer

  def start_link(opts) do
    # 1. Pass the name to GenServer's init
    server = Keyword.fetch!(opts, :name)
    GenServer.start_link(__MODULE__, server, opts)
  end
(...)

Why not write server = opts[:name] ? Is it exclusively to instruct the app to raise a KeyError if not found?

1 Like

Yes, the example relies on the server to have a name, so you would rather crash sooner than later.

  @doc """
  Starts the registry with the given options.

  `:name` is always required.
  """

4 Likes