Rust generics: Expected <T> found <Foo>

半腔热情 提交于 2019-11-29 17:56:53
impl<R> MDBook<R> where R: Renderer {

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

These lines claim that for all types R that implement Renderer, there is a method new(path) that returns MDBook<R>. However, your implementation of the method always returns MDBook<HtmlHandlebars> regardless of what R is.

You could add a trait bound to R (or a method to Renderer) that allows constructing a value of type R in new. Alternatively, the method could accept the renderer as parameter, i.e. fn new(path: &Path, renderer: R) -> Self. Either way, you need a way to get your hands on a renderer (i.e., a value of type R) inside new.

If on the other hand you want to support something like this:

let book = MDBook::new(path);
if some_condition {
    book.set_renderer(SomeOtherThing::new());
}

then generics are the wrong tool for the job, since they make the choice of renderer part of the static type of book. You can remove the R type parameter completely, keep your trait and simply store a trait object (likely Box<Renderer>) in MDBook.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!