This question already has an answer here:
“Expected type parameter” error in the constructor of a generic struct

(1个答案)


5年前关闭。




我有使用泛型的这段代码。
trait RefGen {
    fn gen () -> String;
}

struct FooGen;

impl RefGen for FooGen {
    fn gen () -> String {
        "foo".to_owned()
    }
}

struct Facade<R: RefGen> {
    gen: R
}

impl<R: RefGen> Facade<R> {
    fn new() -> Facade<R> {
        Facade {
            gen: FooGen
        }
    }
}

我不知道为什么Rust告诉我我不能将FooGen用作RefGen。它当然实现了RefGen

确切的错误消息是:
expected `Facade<R>`,
found `Facade<FooGen>`

这是一个围栏:http://is.gd/oBIB1o

最佳答案

这有效:

impl<R: RefGen> Facade<R> {
  fn new(gen: R) -> Facade<R> {
    Facade {
      gen: gen
    }
  }
}

我不确定确切的术语来解释这一点,但是可以理解:在您的代码中,R类型是在new函数内部确定的。但是,Rust要求您从函数外部提供类型。查看以下示例:
// This doesn't typecheck
fn foo1<T: Clone>() -> T {
    "hi"
}

// This works
fn foo2<T: Clone>(x: T) -> T {
    x
}

有关更多详细说明,请参见this answer

10-07 15:12