【问题标题】:Does the 'generic blanket impl of ToString' conflict with the 'impl Tostring for char/str/String...' in rustrust 中的“ToString 的通用总括 impl”是否与“用于 char/str/String 的 impl Tostring ...”冲突
【发布时间】:2021-07-26 04:26:10
【问题描述】:

T 有一个通用的毯子 impl ToString,

impl<T> ToString for T where
    T: Display + ?Sized, 

我还注意到impl ToString for char/str/String...,以及库文档中的许多其他类型https://doc.rust-lang.org/std/string/trait.ToString.html#implementors

它是否与通用的毯子 impl 冲突?

【问题讨论】:

    标签: generics rust implementation


    【解决方案1】:

    显然它不会冲突,因为它可以工作☺

    但你是对的,它应该冲突。有一个名为"specialization" 的功能正在开发中,如果存在多个impl,只要其中一个比其他更具体,编译器就可以解决冲突。在这种情况下,为显式类型(charString)实现比任何泛型 impl&lt;T&gt; for T 更具体,因此它可以工作。

    这个功能还不够稳定,不能用于一般用途,但它的一部分被认为足以在 Rust 标准库中使用,正如您在 the source code for impl ToString for char 中看到的那样:

    #[stable(feature = "char_to_string_specialization", since = "1.46.0")]
    impl ToString for char {
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多