I have a silly question, but I have mostly avoided using ref until now, and only at this point I realize I do not know how to move a value to the heap and get a reference to that value.
For instance, consider the following:
type Foo = object
x: int
proc getFoo(): Foo = Foo(x: 15)
proc getRefFoo(): ref Foo =
let x: ref Foo = getFoo()
x
echo getRefFoo.x
I assumed that inside getFoo, Nim would create the Foo on the heap (because it has to be returned) and hence I would be able to get a reference to it. But the line
let x: ref Foo = getFoo()
does not compile, saying type mismatch: got (Foo) but expected 'ref Foo'. I have tried
let x: ref Foo = ref getFoo()
which is not even syntactically valid, and
let x: ref Foo = addr getFoo()
which fails because addr gives an untraced pointer.
So, if I have a proc that returns a Foo and I need - say - to store it into an object that expects a field of type ref Foo, how do I do this (possibly copying the value if it is not already on the heap)?
The following will work:
type Foo = object
x: int
proc getFoo(): Foo = Foo(x: 15)
proc getRefFoo(): ref Foo =
new result
result[] = getFoo()
echo getRefFoo().x