Rust泛型:预期<T>找到<Foo>

Mat*_*vid 0 generics traits rust

我正在尝试使用泛型,但我不能很好地掌握该主题,并且我收到此错误:

error: mismatched types:
expected `book::mdbook::MDBook<R>`,
found `book::mdbook::MDBook<renderer::html_handlebars::HtmlHandlebars>`
(expected type parameter,
found struct `renderer::html_handlebars::HtmlHandlebars`) [E0308]
Run Code Online (Sandbox Code Playgroud)

这是相关的代码

pub struct MDBook<R> where R: Renderer {
    title: String,
    author: String,
    config: BookConfig,
    pub content: Vec<BookItem>,
    renderer: R,
}

impl<R> MDBook<R> where R: Renderer {

    pub fn new(path: &PathBuf) -> Self {

        MDBook {
            title: String::from(""),
            author: String::from(""),
            content: vec![],
            config: BookConfig::new()
                        .set_src(path.join("src"))
                        .set_dest(path.join("book")),
            renderer: HtmlHandlebars::new(), // <---- ERROR HERE
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Renderer特征目前是空的,实现HtmlHandlebars

pub struct HtmlHandlebars;

impl Renderer for HtmlHandlebars {

}

impl HtmlHandlebars {
    pub fn new() -> Self {
        HtmlHandlebars
    }
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

小智 6

impl<R> MDBook<R> where R: Renderer {

    pub fn new(path: &PathBuf) -> Self {
Run Code Online (Sandbox Code Playgroud)

这些行声称对于所有R实现的类型Renderer,都有一个new(path)返回的方法MDBook<R>.但是,MDBook<HtmlHandlebars>无论是什么,您的方法实现总是返回R.

你可以添加绑定到一个特征R(或方法Renderer),允许建造类型的值Rnew.或者,该方法可以接受渲染器作为参数,即fn new(path: &Path, renderer: R) -> Self.无论哪种方式,您都需要一种方法来获取内部的渲染器(即类型值R)new.

另一方面,如果你想支持这样的事情:

let book = MDBook::new(path);
if some_condition {
    book.set_renderer(SomeOtherThing::new());
}
Run Code Online (Sandbox Code Playgroud)

然后泛型是错误的工具,因为它们选择了渲染器的静态类型book.您可以R完全删除类型参数,保留您的特征并简单地存储特征对象(可能Box<Renderer>)MDBook.