Bit of a noob question but can anyone help me understand why you cannot echo x in the below code but you can echo y. The error message says it expects x to be of type varargs[typed, `$]` and I can then fix it by writing my own toString proc like proc `$`(x:WithRef): string = x.name but I'd just like to know why adding the ref makes this happen.`
type
WithRef = ref object
name: string
NoRef = object
name: string
let
x = WithRef(name: "wren")
y = NoRef(name: "newt")
echo x
echo y
Thank you!
Nim's default $ are implemented for value types not reference types. You could implement:
proc `$`(r: ref): string =
if r.isNil:
"nil"
else:
$r
But this naive approach and will explode when using cyclical types.you forgot to deref r
proc `$`(r: ref): string =
if r.isNil:
"nil"
else:
$r[]
This doesn't answer OP's question: > I'd just like to know why adding the ref makes this happen.`
Is it also left as an exercise to the reader?