首页 > 解决方案 > 如何为关联类型的特征界限的关联类型设置特征界限?

问题描述

我想为关联类型的特征边界的关联类型设置特征边界:

trait UnsafeCast
where
    Self: Sized,
    <Self::Output as TryFrom<Self>>::Error: std::fmt::Debug,
{
    type Output: TryFrom<Self>;
}

当我定义这个函数时,编译器会拒绝它并出现错误:

fn run<T: UnsafeCast>(u: T) -> T::Output {
    T::Output::try_from(u).unwrap()
}

错误是

error[E0277]: `<<T as UnsafeCast>::Output as std::convert::TryFrom<T>>::Error` doesn't implement `std::fmt::Debug`
  --> src/main.rs:9:11
   |
9  |   fn run<T: UnsafeCast>(u: T) -> <T as UnsafeCast>::Output {
   |             ^^^^^^^^^^                                    - help: consider further restricting the associated type: `where <<T as UnsafeCast>::Output as std::convert::TryFrom<T>>::Error: std::fmt::Debug`
   |             |
   |             `<<T as UnsafeCast>::Output as std::convert::TryFrom<T>>::Error` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
...
13 | / trait UnsafeCast
14 | | where
15 | |     Self: Sized,
16 | | <Self::Output as TryFrom<Self>>::Error: std::fmt::Debug,
17 | | {
18 | |     type Output: TryFrom<Self>;
19 | | }
   | |_- required by `UnsafeCast`
   |
   = help: the trait `std::fmt::Debug` is not implemented for `<<T as UnsafeCast>::Output as std::convert::TryFrom<T>>::Error`

错误说我必须设置std::fmt::Debug边界,<T as UnsafeCast>::Output as std::convert::TryFrom<T>>::Error即使我已经在第一个代码中设置了边界。

UnsafeCast编译器还建议在函数定义中添加特征边界,但我认为当我定义使用带有特征边界的类型参数的函数时,它会非常重复。

是否有适当的方法来为上述特征相关类型设置界限?

标签: rusttraitsassociated-types

解决方案


推荐阅读