gpt4 book ai didi

generics - Rust 泛型 : Expected found

转载 作者:行者123 更新时间:2023-11-29 08:22:32 25 4
gpt4 key购买 nike

我正在尝试使用泛型,但我对该主题的掌握不够好,因此出现此错误:

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 trait 目前是空的,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 {

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

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

另一方面,如果你想支持这样的东西:

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

那么泛型是错误的工具,因为它们将渲染器的选择作为 book 的静态类型的一部分。 .您可以删除 R完全输入参数,保留你的特征并简单地存储一个 trait object (可能是 Box<Renderer> )在 MDBook 中.

关于generics - Rust 泛型 : Expected <T> found <Foo>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31490913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com