Runtime-calculated default values for structs

Definitely an interesting perspective! Let me elaborate:

None of them has concept of “default value of an element”. They simply has no similar surface for having a side-effect on creation. Saying this, I started to think where concept of default value is represented in Elixir. Couple of the examples I can think of are:

  • Map.get/3 has static default when value not found
  • Map.put_new_lazy/3 has dynamic default (as a function)

Not sure if those examples are applicable, but it at least some evidence that idea of “dynamic defaults” is not uncommon in Elixir.

Struct is the only user-defined data type. It’s not uncommon to have dynamic defaults for such things in other languages.

  • Ruby: use constructor
  • Python: use constructor (afaik)
  • Golang: structs cannot have defaults at all. A “factory function” is needed to set defaults and they are dynamic.

So, I’d vote for either removing defaults from structs at all to enforce creation of factory functions like in Golang or allow for dynamic defaults to make this feature complete. I expect no one will agree on the first way. =)

So, the answer to the question “why should structs do?” is that they already provide mechanism for defaults, but it’s incomplete. It has restriction that makes it inferior to almost any other popular language. My proposal is about lifting this restriction.

It’s from theoretical perspective. From practical perspective I do not like that it leads to error-prone and/or inconvenient library interfaces.

TBH I do not see how this contradicts with the proposal. =/ I do not propose anything that does things worse than they are from that perspective.