简体   繁体   English

如何绑定关联类型以使用 `?` 运算符?

[英]How can I bound an associated type to work with the `?` operator?

Given the following Rust:给定以下 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()?)
}

I am trying to express that the Fallible::Error type can be converted to an E and therefore should be usable with the ?我试图表达Fallible::Error类型可以转换为E ,因此应该可以与? operator.操作员。 But, for some reason the ?但是,出于某种原因? is based on the From trait, which I'm not sure that it is possible to bound.基于From特征,我不确定是否可以绑定。

This currently fails with:这目前失败:

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`

While you cannot bind at the trait level yet , you can do so on the function:虽然你还不能在特征级别绑定,你可以在 function 上这样做:

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()?)
}

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

相关问题 如何创建运算符来实现错误链接? - How can I create an operator to implement error chaining? 我如何通过将current_user传递给Scope来确保它,从而只给我关联关系数据 - How i Can Ensure the current_user by passing it into Scope So that It gives me only Associated Relation Data 我怎样才能使这个文本变量起作用? - How can I get this text variable to work? 创建使用try运算符的闭包时,如何解决错误“需要类型注释”? - How do I fix the error “type annotations needed” when creating a closure that uses the try operator? 如果args [i]的类型不是Java中预期的类型,如何返回错误消息? 有“类型测试”功能吗? - How can I return an error message if the type of args[i] is not of the expected type in Java? Is there a 'type test' function? 如果发生错误异常,我如何计算执行重试运算符的次数 - How can I count the number of time that was executed retry operator wether the exception of an error occurred 如何使用问号运算符来处理Tokio期货中的错误? - How can I use the question mark operator to handle errors in Tokio futures? 比较线不起作用,为什么? 我该如何解决? - The compare line doesn't work, why? How can I fix it? 如何匹配特定的 io::Error 类型? - How can I match on a specific io::Error type? 如何使用 lm() 修复此无效类型错误? - How can I fix this invalid type error using lm()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM