diff --git a/lib/system.nim b/lib/system.nim index 599c69df6ed81..d036e84282698 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -954,8 +954,23 @@ when defined(nimHasDefault): ## echo @a # => @[1, 3, 5] ## echo @b # => @['f', 'o', 'o'] - proc default*(T: typedesc): T {.magic: "Default", noSideEffect.} - ## returns the default value of the type ``T``. + proc default*(T: typedesc): T {.magic: "Default", noSideEffect.} = + ## returns the default value of the type `T`. + runnableExamples: + assert (int, float).default == (0, 0.0) + # note: `var a = default(T)` is usually the same as `var a: T` and (currently) generates + # a value whose binary representation is all 0, regardless of whether this + # would violate type constraints such as `range`, `not nil`, etc. This + # property is required to implement certain algorithms efficiently which + # may require intermediate invalid states. + type Foo = object + a: range[2..6] + var a1: range[2..6] # currently, this compiles + # var a2: Foo # currently, this errors: Error: The Foo type doesn't have a default value. + # var a3 = Foo() # ditto + var a3 = Foo.default # this works, but generates a `UnsafeDefault` warning. + # note: the doc comment also explains why `default` can't be implemented + # via: `template default*[T](t: typedesc[T]): T = (var v: T; v)` proc reset*[T](obj: var T) {.noSideEffect.} = ## Resets an object `obj` to its default value.