Hi everyone!
I'm working on getting a better hang of generics. I found generics can use type inference if the object is passed as a parameter, but needs to be explicitly stated if it is a return value.
type
Foo = object
foo: int
bar: int
proc init[T](): T =
result = T()
proc stringify[T](o: T):string =
return $o
# fails with "cannot instantiate"
# let t:Foo = init()
# works
let t = init[Foo]()
# works
echo stringify(t)
Is this how it's supposed to work or did I miss something?
Thanks for letting me know! Reported the error message (or the behavior) as a bug <https://github.com/nim-lang/Nim/issues/13683> because I thought it too hard to get confirmation of what's going on, fingers crossed.
As a followup, is it correct that when there are several generic types, and at least one of them is the return type, that all types must be specified to the generic, even if the information would be available to infer both?
type
Foo = object
foo: int
bar: int
Fuz = object
fuz: float
buz: float
proc init[T, U](o: T): U =
discard o
result = U()
# works
let foo = Foo()
let fuz = init[Foo, Fuz](foo)
# fails with "cannot instantiate U" (expected)
# let foo = Foo()
# let fuz:Fuz = init(foo)
# fails with "Error: cannot instantiate: 'init[Fuz]'; got 1 type(s) but expected 2"
# Can this be made to work with a different syntax?
# let foo = Foo()
# let fuz:Fuz = init[Fuz](foo)
echo foo
echo fuz