Nim 2.0+ now has default value support for objects. It looks like this:
type DefaultValues = object
x: int = 2
f: bool = true
The docs state that explicit initialization or the use of the default() proc will use these values. https://nim-lang.org/docs/manual.html#types-default-values-for-object-fields
I wanted to explore exactly what behavior I would get in common scenarios. I think these results may be useful as a reference since I've not seen other posts showing examples of what to expect.
First we have the behavior as described in the docs where the values are set:
echo DefaultValues() # (x: 2, f: true)
echo default(DefaultValues) # (x: 2, f: true)
The following are scenarios where the values are not set:
var a: DefaultValues
echo a # (x: 0, f: false)
# Does `move` set default values when it resets the var?
var b = DefaultValues()
discard move b
echo b # (x: 0, f: false)
proc f(): DefaultValues = # proc `result` behavior
discard
echo f() # (x: 0, f: false)
# array / seq behavior matches `: DefaultValues`, not `= DefaultValues()`
var a: array[1, DefaultValues]
echo a # [(x: 0, f: false)]
I think this behavior can be summed up as "explicit initialization default values" as the docs mention. The thing to be aware of is being sure that explicit initialization has happened since it is easy for it not to.
I wonder if it would be worthwhile to have the compiler issue a warning if an object has default values and one of these scenarios where the default values would not be set is discovered?
For example, it could be very easy to miss a var a: DefaultValues instead of var a = DefaultValues() and not realize you may not get what you are expecting.
Thanks for taking a look.