Skip to content

Commit

Permalink
document default (#16942)
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheecour authored Feb 5, 2021
1 parent ae9ba26 commit 6dc7ece
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions lib/system.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 6dc7ece

Please sign in to comment.