gpt4 book ai didi

error-handling - 为什么在扩展失败类型的结果时得到 "the method exists but the following trait bounds were not satisfied"?

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

我正在尝试添加一个更简洁的 failure crate 的 .with_context(|e| format!("foo: {}", e))到我的代码。像这样playground :

use failure::{Context, Fail, ResultExt}; // 0.1.5

/// Extension methods for failure `Result`.
pub trait ResultContext<T, E> {
/// Wraps the error type in a context type generated by looking at the
/// error value. This is very similar to `with_context` but much more
/// concise.
fn ctx(self, s: &str) -> Result<T, Context<String>>;
}

impl<T, E> ResultContext<T, E> for Result<T, E>
where
E: Fail,
{
fn ctx(self, s: &str) -> Result<T, Context<String>> {
self.map_err(|failure| {
let context = format!("{}: {}", s, failure);
failure.context(context)
})
}
}

pub fn foo() -> Result<i32, failure::Error> {
Ok(5i32)
}

pub fn main() -> Result<(), failure::Error> {
// This works.
let _ = foo().with_context(|_| "foo".to_string())?;
// This doesn't.
foo().ctx("foo")?
}

我收到以下错误:

error[E0599]: no method named `ctx` found for type `std::result::Result<i32, failure::error::Error>` in the current scope
--> src/main.rs:31:11
|
31 | foo().ctx("foo")?
| ^^^
|
= note: the method `ctx` exists but the following trait bounds were not satisfied:
`std::result::Result<i32, failure::error::Error> : ResultContext<_, _>`
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `ctx`, perhaps you need to implement it:
candidate #1: `ResultContext`

我不知道为什么。我或多或少地复制了现有的 with_context 代码。

最佳答案

正如编译器告诉您的那样,Result<i32, failure::error::Error>没有实现 ResultContext<_, _> .您已经为您的实现添加了一个界限:

where
E: Fail,

但是 failure::Error没有实现 failure::Fail :

use failure; // 0.1.5

fn is_fail<F: failure::Fail>() {}

pub fn main() {
is_fail::<failure::Error>();
}
error[E0277]: the trait bound `failure::error::Error: std::error::Error` is not satisfied
--> src/main.rs:6:5
|
6 | is_fail::<failure::Error>();
| ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::error::Error` is not implemented for `failure::error::Error`
|
= note: required because of the requirements on the impl of `failure::Fail` for `failure::error::Error`
note: required by `is_fail`
--> src/main.rs:3:1
|
3 | fn is_fail<F: failure::Fail>() {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

您需要更改边界或类型。

关于error-handling - 为什么在扩展失败类型的结果时得到 "the method exists but the following trait bounds were not satisfied"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56580031/

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