error-handling - 为失败类型扩展 Result 时,为什么我得到“方法存在但不满足以下特征界限”?
问题描述
我正在尝试在我的代码中添加更简洁的failure
crate版本。.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>() {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
你需要改变你的界限或你的类型。
推荐阅读
- javascript - Javascript:根据一定的高度和宽度创建空白图像并获取base64
- excel - ExcelDataReader 更改列名
- python - TypeError:无法解压不可迭代的 Race 对象
- c# - 如何在wfa C#中设置显示工具提示的位置
- html - 忽略样式属性的内容安全策略随机数
- typescript - 从函数类型中省略返回类型?
- r - 为什么子集包含 NA 行但过滤器不包含?
- matrix - Power BI - Matrix Visual - 根据时间戳折叠到最新记录
- antlr - 当存在相似模式时,ANTLR 无法正确匹配模式
- polkadot - Polkadot-JS 导入带派生的 BIP44 地址?