繁体   English   中英

扩展失败类型的结果时,为什么会得到“该方法存在,但以下特征范围不满足”的信息?

[英]Why do I get “the method exists but the following trait bounds were not satisfied” when extending Result for failure types?

我试图在我的代码中添加failure箱的.with_context(|e| format!("foo: {}", e))的更简洁版本。 像这个游乐场

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>() {}
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

您将需要更改边界或类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM