【问题标题】:How can I implement the From trait for all types implementing a trait but use a specific implementation for certain types?如何为实现特征的所有类型实现 From 特征,但对某些类型使用特定实现?
【发布时间】:2018-09-14 22:04:09
【问题描述】:

我正在为包含Cow<str> 的结构实现std::convert::From 特征。有没有办法对所有不同类型的整数使用相同的实现(u8u16u32usize 等等)?

use std::borrow::Cow;

pub struct Luhn<'a> {
    code: Cow<'a, str>,
}

我可以使用绑定在ToString 特征上的特征轻松实现所有整数的代码,但是我不能对strString 使用特定的实现——这样就不能利用Cow 的好处.当我为strString 编写具体实现时,我得到一个编译错误:

error[E0119]: conflicting implementations of trait `std::convert::From<&str>` for type `Luhn<'_>`:
  --> src/lib.rs:23:1
   |
7  | impl<'a> From<&'a str> for Luhn<'a> {
   | ----------------------------------- first implementation here
...
23 | impl<'a, T: ToString> From<T> for Luhn<'a> {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Luhn<'_>`

我知道这是因为 Rust 不提供函数重载。如何以优雅的方式解决这个问题?

impl<'a> From<&'a str> for Luhn<'a> {
    fn from(input: &'a str) -> Self {
        Luhn {
            code: Cow::Borrowed(input),
        }
    }
}

impl<'a> From<String> for Luhn<'a> {
    fn from(input: String) -> Self {
        Luhn {
            code: Cow::Owned(input),
        }
    }
}

impl<'a, T: ToString> From<T> for Luhn<'a> {
    fn from(input: T) -> Self {
        Luhn {
            code: Cow::Owned(input.to_string()),
        }
    }
}

【问题讨论】:

    标签: rust traits


    【解决方案1】:

    由于&amp;strString 都实现了ToString,您可以使用不稳定的specialization 功能:

    #![feature(specialization)]
    
    use std::borrow::Cow;
    
    pub struct Luhn<'a> {
        code: Cow<'a, str>,
    }
    
    impl<'a, T: ToString> From<T> for Luhn<'a> {
        default fn from(input: T) -> Self {
    //  ^^^^^^^
            Luhn {
                code: Cow::Owned(input.to_string()),
            }
        }
    }
    
    impl<'a> From<&'a str> for Luhn<'a> {
        fn from(input: &'a str) -> Self {
            Luhn {
                code: Cow::Borrowed(input),
            }
        }
    }
    
    impl<'a> From<String> for Luhn<'a> {
        fn from(input: String) -> Self {
            Luhn {
                code: Cow::Owned(input),
            }
        }
    }
    

    话虽如此,你不能为Luhn 实现Display,因为你会遇到How is there a conflicting implementation of `From` when using a generic type?

    【讨论】:

    • 非常感谢!除了这个不稳定的特性,有没有办法利用一些特殊的牛属性?或特定的特征。
    猜你喜欢
    • 2019-12-08
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多