Reputation: 2578
I'm just getting started with Nim, and have a problem with generics.
Here is a simplified example that replicates the issue I'm having. Start with a simple object type that has a generic type T
, and make an instance of it:
type Foo[T] = object
bar: T
var my_foo = Foo[string](bar: "foobar")
It works fine if I create a proc
with a generic type T
, and a return value of T
and then return the bar
field of the object, which is type T
:
# This works!
proc test[T](f: Foo, n: int): T =
f.bar
echo test(my_foo, 1)
However, if instead I want to return a sequence of multiple copies of T
that come from the Foo.bar
field which is type T
, like so:
# This fails!
proc test2[T](f: Foo, n: int): seq[T] =
var s: T = f.bar
var r: seq[T] = @[]
for x in 1..n:
r.add(s)
result = r
echo test2(my_foo, 3)
then I get the following error:
Error: cannot instantiate: 'T'
Could anyone please offer any insight as to why this is and how to correctly do this?
Upvotes: 2
Views: 594
Reputation: 5403
Not sure what the internal reasons for this are, but the type inference in Nim may be too local for this. I'd consider it good style to explicitly state the instantiation of Foo
anyway, by writing Foo[T]
instead, like this:
proc test2[T](f: Foo[T], n: int): seq[T] =
Upvotes: 4