document default (#16942)
This commit is contained in:
parent
ae9ba260f6
commit
6dc7ece36a
1 changed files with 17 additions and 2 deletions
|
|
@ -954,8 +954,23 @@ when defined(nimHasDefault):
|
||||||
## echo @a # => @[1, 3, 5]
|
## echo @a # => @[1, 3, 5]
|
||||||
## echo @b # => @['f', 'o', 'o']
|
## echo @b # => @['f', 'o', 'o']
|
||||||
|
|
||||||
proc default*(T: typedesc): T {.magic: "Default", noSideEffect.}
|
proc default*(T: typedesc): T {.magic: "Default", noSideEffect.} =
|
||||||
## returns the default value of the type ``T``.
|
## 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.} =
|
proc reset*[T](obj: var T) {.noSideEffect.} =
|
||||||
## Resets an object `obj` to its default value.
|
## Resets an object `obj` to its default value.
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue