为何编译器无法识别该`From` trait实现?
format_serde_error官方示例编译失败问题
近期尝试使用format_serde_error(用于格式化serde错误信息的Rust crate),发现官方提供的示例代码无法编译。
示例代码
use format_serde_error::SerdeError; use serde::Deserialize; #[derive(Debug, Deserialize)] struct Foo { x: u64, } fn main() { let content = "x: 3"; let foo = serde_yaml::from_str(content) .map_err(|err| SerdeError::new(content.to_string(), err)) .unwrap(); println!("Read in {:?}", foo); }
Cargo.toml配置
[package] name = "ser-test" version = "0.1.0" edition = "2021" [dependencies] format_serde_error = { version = "0.3.0", features = ["serde_yaml"] } serde = { version = "1.0.183", features = ["derive"] } serde_yaml = "0.9.25"
编译错误信息
error[E0277]: the trait bound `ErrorTypes: From<serde_yaml::Error>` is not satisfied --> src/main.rs:12:61 | 12 | .map_err(|err| SerdeError::new(content.to_string(), err)) | --------------- ^^^ the trait `From<serde_yaml::Error>` is not implemented for `ErrorTypes` | | | required by a bound introduced by this call | = help: the following other types implement trait `From<T>`: <ErrorTypes as From<serde_json::error::Error>> <ErrorTypes as From<serde_yaml::error::Error>> <ErrorTypes as From<(Box<(dyn StdError + 'static)>, std::option::Option<usize>, std::option::Option<usize>)>> = note: required for `serde_yaml::Error` to implement `Into<ErrorTypes>` note: required by a bound in `SerdeError::new` --> /home/c/.cargo/registry/src/index.crates.io-6f17d22bba15001f/format_serde_error-0.3.0/src/lib.rs:278:41 | 278 | pub fn new(input: String, err: impl Into<ErrorTypes>) -> SerdeError { | ^^^^^^^^^^^^^^^^ required by this bound in `SerdeError::new`
问题疑惑
编译器提示ErrorTypes未实现From<serde_yaml::Error>,但无论是format_serde_error的仓库代码,还是编译器输出中指向的lib.rs文件,都已定义了该实现:
#[cfg(feature = "serde_yaml")] impl From<serde_yaml::Error> for ErrorTypes { fn from(err: serde_yaml::Error) -> Self { Self::Yaml(err) } }
已尝试将Rust更新至1.73.0-nightly (f3623871c 2023-08-06),执行cargo clean,无论使用默认特性还是显式指定serde_yaml特性,问题均存在。且代码完全复制自format_serde_error的官方示例。
复现步骤
cargo new ser-test cd ser-test cargo add serde --features derive cargo add serde_yaml cargo add format_serde_error # 将上述示例代码复制到src/main.rs中 cargo run
内容的提问来源于stack exchange,提问作者Carson
相关产品推荐
相关产品推荐

