Here's an example of using fieldPairs to dump a custom debug of an object:
type
Custom = object
foo, bar: string
proc `$`(x: Custom): string =
result = "Custom:"
for name, value in x.fieldPairs:
if value.isNil:
result.add("\n\t" & name & " (nil)")
else:
result.add("\n\t" & name & " '" & value & "'")
proc test() =
var x: Custom
x.foo = "Foo"
echo x
when isMainModule: test()
This works until the Custom type grows a foobar: bool field, it stops compiling with:
stru.nim(9, 12) Error: type mismatch: got (bool)
but expected one of:
system.isNil(x: pointer): bool
system.isNil(x: T): bool
system.isNil(x: seq[T]): bool
system.isNil(x: cstring): bool
system.isNil(x: string): bool
system.isNil(x: ptr T): bool
system.isNil(x: ref T): bool
How is one meant to branch inside the loop according to the types? Can case be used for that? Also, the docstring mentions there is a bug which affects symbol binding. Can somebody elaborate on what this bug is and how it affects the code?Try this:
type
Custom = object
foo, bar: string
foobar: bool
proc `$$`(v: bool): string =
"'" & $v & "'"
proc `$$`[T: ref|string](v: T): string =
if v.isNil:
"(nil)"
else:
"'" & $v & "'"
proc `$`(x: Custom): string =
result = "Custom:"
for name, value in x.fieldPairs:
result.add("\n\t" & name & " " & $$(value))
proc test() =
var x: Custom
x.foo = "Foo"
echo x
when isMainModule: test()
Yeah, proc overload FTW. I was hoping there was a shorter syntax. Tried something like when value.type == bool.type but the compiler tells me typedescs can't be compared. I guess typedescs are meant only for proc overloads too.
Mysterious bug is still mysterious.
gradha: Tried something like when value.type == bool.type but the compiler tells me typedescs can't be compared.
You can do when value.type is bool instead.