Nim lacks a concise ref object constructor. We can do
type Foo = object
val: int
let f = Foo(val: 13)
but to create a ref Foo I either need to create a separate ref Foo type, or use code like
let f = new Foo
f.val = 13
Leorize suggested the following snippet for this:
proc new[T: ref object | object](o: sink T): auto =
when T is ref:
result = o
else:
result = new(T)
result[] = o
This would allow new to work as a ref object constructor like so:
let f = new Foo(val: 13)
Any feedback on this appreciated, could something like this go in system.nim?
type Foo = object
val: int
let f = (ref Foo)(val: 13)
Most helpful comment