如何绑定关联类型以使用"?"操作员



给定以下Rust:

struct E;
trait Fallible {
type Error: Into<E>;
fn e(&self) -> Result<(), Self::Error>;
}
fn test(f: &impl Fallible) -> Result<(), E> {
Ok(f.e()?)
}

我试图表达Fallible::Error类型可以转换为E,因此应该与?运算符一起使用。但是,由于某种原因,?是基于From特性的,我不确定它是否可能绑定。

此操作当前失败:

error[E0277]: `?` couldn't convert the error to `E`
--> src/lib.rs:9:13
|
9 |     Ok(f.e()?)
|             ^ the trait `std::convert::From<<impl Fallible as Fallible>::Error>` is not implemented for `E`
|
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= note: required by `std::convert::From::from`

虽然您还不能在特性级别进行绑定,但您可以在函数上进行绑定:

struct E;
trait Fallible {
type Error: Into<E>;
fn e(&self) -> Result<(), Self::Error>;
}
fn test<T>(f: &T) -> Result<(), E>
where
T: Faillible,
E: From<T::Error>,
{
Ok(f.e()?)
}

最新更新