mirror of
https://github.com/nim-lang/Nim.git
synced 2026-01-03 11:42:33 +00:00
document default (#16942)
This commit is contained in:
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user