簡體   English   中英

如何為實現特征的所有類型實現From特質,但對某些類型使用特定的實現?

[英]How can I implement the From trait for all types implementing a trait but use a specific implementation for certain types?

我正在為包含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()),
        }
    }
}

由於&strString都實現ToString ,因此可以使用不穩定的專業化功能:

#![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 for Luhn因為您在使用泛型類型時會遇到“ From”的沖突實現嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM