3 ms·
> Am I right in thinking that every instance of BlogPost type must be constructed explicitly in your code? I.e. that every possible instance of BlogPost in the
by arrowsmith 2y ago
> Am I right in thinking that every instance of BlogPost type must be constructed explicitly in your code? I.e. that every possible instance of BlogPost in the code base is knowable at compile time, along with its entire life cycle?
Almost. You can create a struct dynamically at runtime like this:
struct(BlogPost, %{title: "The Title"})
# => %BlogPost{title: "The Title"}
… but you rarely need to. In fact I'm not sure I've ever used `struct/2` in real life. 99.9% of all the structs you ever create will have their types known at compile-time.
> any conforming untyped map of indeterminate provenance will pass the guard check for a BlogPost?
Nope. In the `add_comment/2` example, If I pass anything except a %BlogPost{} to that function, I'll get an error.
- troad 2y agoI appreciate the explanation, you're a champ. :) While I remain haunted by thoughts of someone e.g. deserialising a YAML file into a map, which then sneaks in some __struct__ key and squeaks past the guard clause, I also appreciate this seems fairly unlikely in practice. I think I'm just traumatised by Rails. It sounds like the culture around Elixir eschews excessive cutesiness, though. Promising!
- arrowsmith 2y agoDon't let your experience with Ruby colour your opinion of Elixir. Elixir's similarity to Ruby (and Phoenix's to Rails) is hugely overstated. I wrote a long Reddit post about that[0], but for the tl;dr you can ask José Valim himself: https://news.ycombinator.com/item?id=36604054 https://news.ycombinator.com/item?id=36604054 [0] https://old.reddit.com/r/elixir/comments/1ipyi81/why_should_i_use_phoenix_for_my_saas/mcvyzjn/ https://old.reddit.com/r/elixir/comments/1ipyi81/why_should_...