Nim lacks ref object constructor

Created on 8 Feb 2020  路  1Comment  路  Source: nim-lang/Nim

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?

Most helpful comment

type Foo = object
  val: int

let f = (ref Foo)(val: 13)

>All comments

type Foo = object
  val: int

let f = (ref Foo)(val: 13)
Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  4Comments

hlaaftana picture hlaaftana  路  3Comments

kobi2187 picture kobi2187  路  4Comments

zaxebo1 picture zaxebo1  路  4Comments

teroz picture teroz  路  3Comments