如何为实现特征的所有类型实现From特征,但是对某些类型使用特定实现?

问题描述 投票:0回答:1

我正在为包含std::convert::From的结构实现Cow<str>特性。有没有办法对所有不同类型的整数使用相同的实现(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个回答
2
投票

由于&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),
        }
    }
}

话虽这么说,你不能为Display实施Luhn,因为你遇到了How is there a conflicting implementation of `From` when using a generic type?

© www.soinside.com 2019 - 2024. All rights reserved.