summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorringabout <43030857+ringabout@users.noreply.github.com>2022-11-15 15:42:01 +0800
committerGitHub <noreply@github.com>2022-11-15 08:42:01 +0100
commit4a3be7e29eb25b04a5542e7b92605c5ee24620bb (patch)
tree08ce107bfc59e5e0d77dd459828ae057e1d28eca
parent32b145460f21643f08468dd80fd4c76917c6bbfc (diff)
downloadNim-4a3be7e29eb25b04a5542e7b92605c5ee24620bb.tar.gz
add documentation and changelog for default object fields (#20845)
-rw-r--r--changelog.md2
-rw-r--r--doc/manual.md51
2 files changed, 53 insertions, 0 deletions
diff --git a/changelog.md b/changelog.md
index 16bafd8a2..b6e306334 100644
--- a/changelog.md
+++ b/changelog.md
@@ -102,6 +102,8 @@
 
 - `logging` will default to flushing all log level messages. To get the legacy behaviour of only flushing Error and Fatal messages, use `-d:nimV1LogFlushBehavior`.
 
+- Object fields now support default values, see https://nim-lang.github.io/Nim/manual.html#types-default-values-for-object-fields for details.
+
 ## Standard library additions and changes
 
 [//]: # "Changes:"
diff --git a/doc/manual.md b/doc/manual.md
index bd5307003..a4f864eaa 100644
--- a/doc/manual.md
+++ b/doc/manual.md
@@ -1950,6 +1950,57 @@ Some restrictions for case objects can be disabled via a `{.cast(uncheckedAssign
     t.kind = intLit
   ```
 
+Default values for object fields
+--------------------------------
+
+Object fields are allowed to have a constant default value. The type of field can be omitted if a default value is given.
+
+```nim test
+type
+  Foo = object
+    a: int = 2
+    b: float = 3.14
+    c = "I can have a default value"
+
+  Bar = ref object
+    a: int = 2
+    b: float = 3.14
+    c = "I can have a default value"
+```
+
+The explicit initialization uses these defaults which includes an `object` created with an object construction expression or the procedure `default`; a `ref object` created with an object construction expression or the procedure `new`; an array or a tuple with a subtype which has a default created with the procedure `default`.
+
+
+```nim test
+type
+  Foo = object
+    a: int = 2
+    b = 3.0
+  Bar = ref object
+    a: int = 2
+    b = 3.0
+
+block: # created with an object construction expression
+  let x = Foo()
+  assert x.a == 2 and x.b == 3.0
+
+  let y = Bar()
+  assert y.a == 2 and y.b == 3.0
+
+block: # created with an object construction expression
+  let x = default(Foo)
+  assert x.a == 2 and x.b == 3.0
+
+  let y = default(array[1, Foo])
+  assert y[0].a == 2 and y[0].b == 3.0
+
+  let z = default(tuple[x: Foo])
+  assert z.x.a == 2 and z.x.b == 3.0
+
+block: # created with the procedure `new`
+  let y = new Bar
+  assert y.a == 2 and y.b == 3.0
+```
 
 Set type
 --------