![](/img/trans.png)
[英]Why doesn't my implementation of TryFrom<Vec<T>> cover TryFrom<Vec<String>>?
[英]Unexpected conflicting implementation for TryFrom
我想在這樣的情況下實現特征TryFrom
:
struct T1;
struct T2(T1);
impl<U> TryFrom<U> for T2 where U: Into<T1> {
type Error = ();
fn try_from(val:U) -> Result<T2, Self::Error> {
unimplemented!();
}
}
這給了我這個錯誤:
error[E0119]: conflicting implementations of trait `std::convert::TryFrom<_>` for type `T2`
--> src/lib.rs:4:1
|
4 | impl<U> TryFrom<U> for T2 where U: Into<T1> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: conflicting implementation in crate `core`:
- impl<T, U> TryFrom<U> for T
where U: Into<T>;
這里U
實現Into<T1>
而不是Into<T2>
因此我不太了解錯誤。 我試圖通過實現它來確認沒有一攬子實現,它編譯時沒有沖突:
struct T1;
struct T2(T1);
impl Into<T2> for T1 {
fn into(self) -> T2 {
unimplemented!();
}
}
有什么辦法嗎? 我不想要這里的默認實現。
特征實現不允許發生沖突。 一個類型完全可以實現Into<T1>
和Into<T2>
。 在這種情況下,您的實現會導致歧義,無論是通過內置的一攬子實現還是從您的一攬子實現來使用T: TryFrom<U>
實現。 因此存在沖突,編譯器會拒絕您的實現。
本質上,由於一攬子實現,您不能通用地實現TryFrom
; 你無法避免潛在的沖突。
您的確認沒有任何意義,因為Into
沒有這樣的全面實施會在T1
和T2
之間發生沖突。 如果您嘗試通用地實現它,例如impl Into<T2> for U where U: Into<T1>
,那也是一個問題。 泛型是核心問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.