mirror of
https://github.com/nim-lang/Nim.git
synced 2025-12-30 18:02:05 +00:00
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>
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user