Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct struct definition

Tags:

elixir

How to define the struct in the correct way, look at the following code snippet:

defmodule SapOdataService.Worker do
  defstruct uri: "", user: nil, password: nil

Should I define the default value as nil or?

like image 449
softshipper Avatar asked Jan 05 '23 21:01

softshipper


1 Answers

You have a few options.

  1. You can list the key value pairs explicitly using nil for blank values

    defmodule User do
      defstruct name: "zero_coding", age: nil
    end
    
  2. You can pass a list of atoms that will all default to nil:

    defmodule User do
      defstruct [:name, :age]
    end
    
  3. You can do a mix of the above a list of atoms that will all default to nil:

    defmodule User do
      defstruct [:age, name: "zero_coding"] 
    end
    
  4. You can also enforce specific keys that must be specified when creating the struct

    defmodule User do
      @enforce_keys [:name]
      defstruct [:name, :age]
    end
    
like image 71
fny Avatar answered Mar 11 '23 04:03

fny