stevensonmt
Defining types for struct fields
I would like to have a struct in a module without default values for the fields, but I would like each field to be limited to a specific type. Is there a way to define and enforce this in Elixir?
Most Liked
lud
You can define a typespec for your struct but you cannot enforce it.
What you can do in your module is to use a constructor-like function:
def new(props) do
... validate the values
struct(__MODULE__, props)
end
(new is not a special name)
hauleth
lud
I hesitated because if you validate the values beforehand you should not have to use it, but yes it may be safer.
@stevensonmt the difference is that struct!/2 will raise if the given props have extra properties or if keys declared with @enforce_keys are not defined.
Last Post!
RudManusachi
It depends. While, IMHO, it’s easier to begin with case do, if the body of different branches of case is getting larger it’s nicer to break it into multiple functions. Plus multiple functions if fail - will give you better backtrace info on where to look at. Also, to me, it’s somewhat easier to read when the whole body of the function describes one path rather than keeping condition context in mind.
Or, just whatever is easier to read =)
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









