Skip to content

defstruct sets @enforce_keys to nil #12126

@lud

Description

@lud

Elixir and Erlang/OTP versions

Erlang/OTP 25 [erts-13.0.4] [source] [64-bit] [smp:16:16] [ds:16:16:10] [async-threads:1] [jit:ns]

Elixir 1.14.0 (compiled with Erlang/OTP 25)

Operating system

xUbuntu 21.04

Current behavior

The new/1 function will fail because @enforce_keys is nil.

defmodule X do
  @enforce_keys [:a, :b, :c]
  IO.inspect(@enforce_keys, label: "@enforce_keys before")
  defstruct @enforce_keys
  IO.inspect(@enforce_keys, label: "@enforce_keys after ")

  def new(vars) do
    case Keyword.drop(vars, @enforce_keys) do
      [] -> struct!(__MODULE__, vars)
      list -> SomeModule.raise_unknown_opts(vars)
    end
  end
end
X.new(x: 1)

** (FunctionClauseError) no function clause matching in Keyword.drop/2    
    
    The following arguments were given to Keyword.drop/2:
    
        # 1
        [x: 1]
    
        # 2
        nil
    
    Attempted function clauses (showing 1 out of 1):
    
        def drop(keywords, keys) when is_list(keywords) and is_list(keys)

Expected behavior

It worked as expected with the following versions

elixir 1.13.4-otp-25
erlang 25.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions