我正在尝试使用泛型,但我对这个主题掌握得不够好,我得到了以下错误:
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]这是相关的代码
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
}
}
}目前,Renderer特性是空的,HtmlHandlebars的实现是
pub struct HtmlHandlebars;
impl Renderer for HtmlHandlebars {
}
impl HtmlHandlebars {
pub fn new() -> Self {
HtmlHandlebars
}
}我做错了什么?
发布于 2015-07-18 12:06:47
impl<R> MDBook<R> where R: Renderer {
pub fn new(path: &PathBuf) -> Self {这些行声称,对于实现R的所有类型的Renderer,都有一个返回MDBook<R>的方法new(path)。但是,方法的实现总是返回MDBook<HtmlHandlebars>,而不管R是什么。
您可以添加绑定到R (或Renderer的方法)的特性,该特性允许在new中构造R类型的值。或者,该方法可以接受渲染器作为参数,即fn new(path: &Path, renderer: R) -> Self。无论哪种方式,您都需要一种方法在new中获取渲染器(即类型为new的值)。
另一方面,如果您想支持这样的东西:
let book = MDBook::new(path);
if some_condition {
book.set_renderer(SomeOtherThing::new());
}然后泛型是作业的错误工具,因为它们选择静态类型的book的呈现器部分。您可以完全删除R类型参数,保留您的特性,只需将特征对象 (可能是Box<Renderer>)存储在MDBook中。
https://stackoverflow.com/questions/31490913
复制相似问题