User types should support a static "factory" method which is called automatically for default initialization. #22031
JalonSolov
started this conversation in
Ideas
Replies: 1 comment
-
I think its good to have static factory explicitly called by user with predefined behaviour ....and fallback to default value with default behaviour of instantiated factory |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Discord discussion starts here: https://discord.com/channels/592103645835821068/592106336838352923/1272226772951367791
The idea is that if a user type (struct, sum type, alias, etc.) has a static method with a particular name (which could be
new
,init
, or whatever), this method will be called when assigning a default value.For example, right now, if you have a struct like this
then instantiate that struct with a simple
then
my_field
will be assigned a value of0
.You can currently change the default by explicitly assigning a default value, such as
in which case
will should
my_field
with a value of7
.This is fine for simple assignments, but if you want something more complex (especially with a struct with more fields, perhaps the values of some rely on the values set for others, etc.), a static "factory" method would make more sense.
The main problem with a static "factory" method currently is that the user both has to know it exists, and has to explicitly call it.
If the compiler would call it automatically when a type is instantiated, this would resolve that issue. If the static method didn't exist, then the current default 0 would still apply.
Thoughts?
Beta Was this translation helpful? Give feedback.
All reactions