如何为关联类型的特征绑定的关联类型设置特征边界?

时间:2020-03-27 15:02:44

标签: rust traits associated-types

我要为关联类型的特征范围的关联类型设置特征范围:


import sys
def read_numb():
    while True:
        try:
            i1 = sys.argv[1]
            x = float(i1)
            break
        except ValueError:
            raise ValueError("Oops!  %s was no valid number. " % i1)
        except IndexError:
            raise IndexError("You must give a value!")

try:
    read_numb()
except Exception as e:
    print(e)

当我定义此函数时,编译器会因错误而拒绝它:

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特征范围的类型参数的函数时,这将是非常重复的。

是否有一种合适的方法来为上述特质相关类型设置界限?

0 个答案:

没有答案