Rust 泛型:预期 <T> 发现 <Foo>
Rust generics: Expected <T> found <Foo>
我正在尝试使用泛型,但我对该主题的掌握不够好,因此出现此错误:
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
}
}
我做错了什么?
impl<R> MDBook<R> where R: Renderer {
pub fn new(path: &PathBuf) -> Self {
这些行声称 对于实现 Renderer
的所有 类型 R
,有一个方法 new(path)
returns MDBook<R>
。但是,无论 R
是什么,您对该方法的实施总是 returns MDBook<HtmlHandlebars>
。
您可以添加绑定到 R
的特征(或绑定到 Renderer
的方法),允许在 new
中构造类型为 R
的值。或者,该方法可以接受渲染器作为参数,即 fn new(path: &Path, renderer: R) -> Self
。无论哪种方式,您都需要一种方法来获取 new
.
内的渲染器(即 R
类型的值)
如果另一方面你想支持这样的东西:
let book = MDBook::new(path);
if some_condition {
book.set_renderer(SomeOtherThing::new());
}
那么泛型是不适合这项工作的工具,因为它们使渲染器的选择成为 book
静态类型的一部分。您可以完全删除 R
类型参数,保留您的特征并在 MDBook
.
中简单地存储一个 trait object (可能 Box<Renderer>
)
我正在尝试使用泛型,但我对该主题的掌握不够好,因此出现此错误:
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
}
}
我做错了什么?
impl<R> MDBook<R> where R: Renderer {
pub fn new(path: &PathBuf) -> Self {
这些行声称 对于实现 Renderer
的所有 类型 R
,有一个方法 new(path)
returns MDBook<R>
。但是,无论 R
是什么,您对该方法的实施总是 returns MDBook<HtmlHandlebars>
。
您可以添加绑定到 R
的特征(或绑定到 Renderer
的方法),允许在 new
中构造类型为 R
的值。或者,该方法可以接受渲染器作为参数,即 fn new(path: &Path, renderer: R) -> Self
。无论哪种方式,您都需要一种方法来获取 new
.
R
类型的值)
如果另一方面你想支持这样的东西:
let book = MDBook::new(path);
if some_condition {
book.set_renderer(SomeOtherThing::new());
}
那么泛型是不适合这项工作的工具,因为它们使渲染器的选择成为 book
静态类型的一部分。您可以完全删除 R
类型参数,保留您的特征并在 MDBook
.
Box<Renderer>
)