gpt4 book ai didi

Rust 特性不满足

转载 作者:行者123 更新时间:2023-12-03 11:27:36 25 4
gpt4 key购买 nike

我是 Rust 的新手,尝试在 stackoverflow 中搜索以及阅读 serde 文档 https://docs.serde.rs/serde/trait.Serialize.htmlhttps://serde.rs/impl-serialize.html ,但我有点迷路。

我想使用 Tera 生成 html,而我传递给它的结构没有实现 serde::ser::Serialize 特性,我试图实现它,但它没有'看起来不太对。

Cargo.toml 依赖

serde = "1.0.115"
serde_derive = "1.0.115"
serde-xml-rs = "0.4.0"
tera = "0.7.2"

主要.rs

extern crate tera;
#[macro_use]
extern crate serde_derive;
extern crate serde;

use tera::Context;
use serde::ser::{Serialize, SerializeStruct, Serializer};

#[derive(Serialize, Debug)]
struct Person {
firstname: String,
lastname: String,
age: i32,
}

#[derive(Debug)]
struct Attendees {
people: Vec<Person>,
updatedOn: String,
updatedBy: String,
}

impl Serialize for Attendees {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut s = serializer.serialize_struct("Person", 3)?;
s.serialize_field("people", &self.people)?;
s.serialize_field("updatedOn", &self.updatedOn)?;
s.serialize_field("updatedBy", &self.updatedBy)?;
s.end()
}
}

fn main() {
let mut context = Context::new();
let mut peeps: Vec<Person> = Vec::new();
let mut attendees = Attendees {
people: peeps,
updatedOn: String::from("today"),
updatedBy: String::from("someone"),
};
context.add("attendees", &attendees);
}

编译器说:

mytest % cargo run      
Compiling mytest v0.1.0 (/home/mike/mytest)
error[E0277]: the trait bound `Attendees: serde::ser::Serialize` is not satisfied
--> src/main.rs:44:29
|
44 | context.add("attendees", &attendees);
| ^^^^^^^^^^ the trait `serde::ser::Serialize` is not implemented for `Attendees`

error: aborting due to previous error

我显然遗漏了一些东西......任何人都可以帮忙吗?

最佳答案

您实现的特征和错误所指的特征不一样,因为它们指的是两个不同版本的 serde。

[[package]]
name = "tera"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c37e2aaa53871f9c3722a20f8951fea0afd366955e11542a58feb71997c6d769"
dependencies = [
"chrono",
"error-chain",
"glob",
"humansize",
"lazy_static 0.2.11",
"pest",
"regex",
"serde 0.9.15",
"serde_json",
"slug",
"url",
]

tera 0.7.2 使用的不是 serde 的 1.0.* 版本,而是 0.9.*

您可以使用更新的 tera,或者在您的 Cargo.toml 中使用兼容的 serde 版本:

[dependencies]
serde = "0.9.15"
serde_derive = "0.9.15"

关于Rust 特性不满足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63445641/

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