Skip to content

Commit 6dc7ece

Browse files
authored
document default (#16942)
1 parent ae9ba26 commit 6dc7ece

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

lib/system.nim

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -954,8 +954,23 @@ when defined(nimHasDefault):
954954
## echo @a # => @[1, 3, 5]
955955
## echo @b # => @['f', 'o', 'o']
956956

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)`
959974

960975
proc reset*[T](obj: var T) {.noSideEffect.} =
961976
## Resets an object `obj` to its default value.

0 commit comments

Comments
 (0)