4

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?

5
  • 2
    Depends on your usecase, you can define custom default values or just pass a list of atoms to the defstruct and every value will have a nil as a default, which may make sense in your case I guess. Commented Dec 19, 2016 at 12:44
  • What is mean depends on my case? Commented Dec 19, 2016 at 12:47
  • Well, sometimes, for let's say url value it makes sense to leave nil as a default value, sometimes it makes sense to make "example.com" as a default value, sometimes it makes sense to make it an empty string and etc. It's completely up to you and what you think it more suitable for your situation. Commented Dec 19, 2016 at 13:53
  • 5
    You can also combine both and write something like defstruct [:user, :password, url: ""], so you don't have to repeat nil over and over. Commented Dec 19, 2016 at 14:37
  • Thanks so much guys. Commented Dec 19, 2016 at 15:42

1 Answer 1

9

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 
Sign up to request clarification or add additional context in comments.

1 Comment

here type 3 only works if you put first all the default-less (implicit nil) first, then the explicit defaults. defstruct [name: "zero_coding", :age] gives error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.