简体   繁体   English

为什么无法推断泛型?

[英]Why is a generic type unable to be inferred?

I'm just getting started with Nim, and have a problem with generics. 我刚刚开始使用Nim,并且对泛型有疑问。

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: 从具有通用类型T的简单对象类型开始,并使其成为实例:

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 : 如果我创建了一个它工作正常proc与通用型T ,以及一个返回值T ,然后返回bar的对象,它的类型是场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: 但是,如果相反,我想返回T的多个副本序列,这些序列来自Foo.bar字段,类型为T ,如下所示:

# 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' 错误:无法实例化:“ T”

Could anyone please offer any insight as to why this is and how to correctly do this? 任何人都可以提供关于这是为什么以及如何正确执行此操作的任何见解?

Not sure what the internal reasons for this are, but the type inference in Nim may be too local for this. 不确定造成这种情况的内部原因是什么,但是Nim中的类型推断对此可能太本地化了。 I'd consider it good style to explicitly state the instantiation of Foo anyway, by writing Foo[T] instead, like this: 我认为通过写Foo[T]来显式声明Foo的实例是一种好风格,例如:

proc test2[T](f: Foo[T], n: int): seq[T] =

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM