Am I doing something silly here or recursive constructors are not allowed?
type T = object
x: int
children: seq[T]
proc new(self: type T, x: int): T =
result.x = x
if x == 1:
result.children = @[ T.new(x + 1) ]
let t = T.new(1)
echo t
# recur.nim(10, 10) template/generic instantiation from here
# recur.nim(8, 27) Error: ambiguous call; both recur.new(self: typedesc[T], x: int) and new.new(self: typedesc[T], x: int) match for: (typedesc[T], int)
Simple function of course works fine:
proc foo(i: int) =
echo i
if i < 3:
foo(i + 1)
foo(1)
# 1
# 2
# 3
Works when you use typedesc instead of type T. Where is type T documented?
It also works when you use another identifier than new.
Thanks for your help @def and @boia01. So what's the idiomatic way of defining constructors in Nim?
I don't want to make generic constructor like this. This for example works for Node2 but I would like the constructor to work only for Node:
type Node = object
value: int
children: seq[Node]
type Node2 = object
value: int
children: seq[Node2]
proc new(Node: typedesc, value: int): Node =
result.value = value
if value == 1:
result.children = @[ Node.new(value + 1) ]
let t = Node.new(1)
let t2 = Node2.new(1) # works as well but I'd like constructor to be defined on Node only.
echo t
echo t2
I guess I'm going to go through manual(s) so I don't ask silly questions like this...