如何绑定关联类型以与 `?` 运算符一起使用?
How can I bound an associated type to work with the `?` operator?
给定以下 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`
虽然您不能在特征级别绑定 yet,但您可以在函数上这样做:
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()?)
}
给定以下 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`
虽然您不能在特征级别绑定 yet,但您可以在函数上这样做:
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()?)
}