@@ -954,8 +954,23 @@ when defined(nimHasDefault):
954
954
# # echo @a # => @[1, 3, 5]
955
955
# # echo @b # => @['f', 'o', 'o']
956
956
957
- proc default * (T: typedesc ): T {.magic : " Default" , noSideEffect .}
958
- # # returns the default value of the type ``T``.
957
+ proc default * (T: typedesc ): T {.magic : " Default" , noSideEffect .} =
958
+ # # returns the default value of the type `T`.
959
+ runnableExamples:
960
+ assert (int , float ).default == (0 , 0.0 )
961
+ # note: `var a = default(T)` is usually the same as `var a: T` and (currently) generates
962
+ # a value whose binary representation is all 0, regardless of whether this
963
+ # would violate type constraints such as `range`, `not nil`, etc. This
964
+ # property is required to implement certain algorithms efficiently which
965
+ # may require intermediate invalid states.
966
+ type Foo = object
967
+ a: range [2 .. 6 ]
968
+ var a1: range [2 .. 6 ] # currently, this compiles
969
+ # var a2: Foo # currently, this errors: Error: The Foo type doesn't have a default value.
970
+ # var a3 = Foo() # ditto
971
+ var a3 = Foo .default # this works, but generates a `UnsafeDefault` warning.
972
+ # note: the doc comment also explains why `default` can't be implemented
973
+ # via: `template default*[T](t: typedesc[T]): T = (var v: T; v)`
959
974
960
975
proc reset * [T](obj: var T) {.noSideEffect .} =
961
976
# # Resets an object `obj` to its default value.
0 commit comments