Skip to content

document default(T) #16942

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 5, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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