我可以为泛型类型实现泛型 From<> 特征,以用于除自身之外的任何其他实现吗?

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

我制作了一个通用的 Vector 结构,与不同的 T 类型一起使用:

struct Vector<T> {
    data: [T; 3],
}

我已经实现了数学操作数的一些通用特征(

Eq
Index
std::ops::Add
...)并且效果很好。

但是现在,我正在努力实现

From
特征,以便我可以轻松地将向量转换为向量。

impl<T, U> From<Vector<U>> for Vector<T> {
    fn from(item: Vector<U>) -> Self {
        // [...]
    }
}

无论这个

from
函数的实现如何,我都会收到以下错误:

error[E0119]: conflicting implementations of trait `From<Vector<_>>` for type `Vector<_>`
 --> <source>:5:1
  |
5 | impl<T, U> From<Vector<U>> for Vector<T> {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: conflicting implementation in crate `core`:
          - impl<T> From<T> for T;

如果我理解正确的话,这是因为默认情况下,对于任何类型,

From<Vector<T>> for Vector<T>
已经被声明了。如果
T
U
是相同的类型,我的实现会与之冲突。

那么有没有办法将我的实现用于任何不同类型

T
U
,但不将其用于相同类型
T
U

templates rust type-conversion
1个回答
0
投票

您无法编写此实现。

即使您是

From
的所有者,您也无法编写此界限,因为它与
impl<T> From<T> for T
(其中
T == U
)冲突。事实上,有些人希望标准库为集合编写这个 impl(例如,
Option<T>
),尽管标准库是
From
的所有者,但它无法提供这个 impl。

您可以提供一种方法来做到这一点,而不是特征实现。

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