summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authordawidkotlin <75385975+dawidkotlin@users.noreply.github.com>2021-02-19 07:59:33 +0100
committerGitHub <noreply@github.com>2021-02-19 07:59:33 +0100
commit95664e15247d678476d64a1c81f7c19b163e823c (patch)
tree1c76bf7ff89eaaba5fc864b97e4360cdc332c082 /lib
parent9450bf6c08cda9b368a1b3276b570dc6ce039193 (diff)
downloadNim-95664e15247d678476d64a1c81f7c19b163e823c.tar.gz
add example of hashing an object by all of its fields with `fields` (#16643)
* add example of hashing an object by all of its fields with `fields`

* Update lib/pure/hashes.nim

* Update lib/pure/hashes.nim

* Update lib/pure/hashes.nim

Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>
Co-authored-by: Timothee Cour <timothee.cour2@gmail.com>
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/hashes.nim14
1 files changed, 14 insertions, 0 deletions
diff --git a/lib/pure/hashes.nim b/lib/pure/hashes.nim
index 3cf0a8f82..54e083d25 100644
--- a/lib/pure/hashes.nim
+++ b/lib/pure/hashes.nim
@@ -54,6 +54,20 @@ runnableExamples:
 ## **Note:** If the type has a `==` operator, the following must hold:
 ## If two values compare equal, their hashes must also be equal.
 ##
+## You can hash an object by all of its fields with the `fields` iterator:
+runnableExamples:
+  proc hash(x: object): Hash =
+    for f in fields(x):
+      result = result !& hash(f)
+    result = !$result
+
+  type
+    Obj = object
+      x: int
+      y: string
+
+  doAssert hash(Obj(x: 520, y: "Nim")) != hash(Obj(x: 520, y: "Nim2"))
+
 ## See also
 ## ========
 ## * `md5 module <md5.html>`_ for the MD5 checksum algorithm