Rust 进入实现冲突核心

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

我有一个类似枚举的结果:

enum Choice<A, B> {
    A(A),
    B(B),
} 

如果两个泛型都是 T,我希望此类型实现 Into。
尝试1:

impl<T> Into<T> for Choice<T, T> {
    fn into(self) -> T {
        let (Choice::A(x) | Choice::B(x)) = self;
        x
    }
}

让我明白:

conflicting implementation in crate `core`:
            - impl<T, U> Into<U> for T
              where U: From<T>;

尝试2:

impl<T> From<Choice<T, T>> for T {
    fn from(x: Choice<T, T>) -> Self {
        let (Choice::A(x) | Choice::B(x)) = x;
        x
    }
}

让我明白:

implementing a foreign trait is only possible if at least one of the types  
for which it is implemented is local, and no uncovered type parameters  
appear before that first local type
rust
1个回答
0
投票

您无法实施

Into
,因为全面实施了
std::core
。该错误提示您需要做什么才能使用该一揽子实现:

conflicting implementation in crate `core`:
            - impl<T, U> Into<U> for T
              where U: From<T>;

在这种情况下,

U
Choice<T, T>
。所以你必须为
From<T>
实现
Choice
。您的第二次尝试为所有
From
提供了
T
的全面实现,这是不允许的(结构的特征必须是您的板条箱的一部分)。

enum Choice<A, B> {
    A(A),
    B(B),
}

impl<T> From<T> for Choice<T, T> {
    fn from(value: T) -> Self {
        Self::A(value)
    }
}

fn main() {
    let _: Choice<i32, i32> = Choice::from(100);
    let _: Choice<i32, i32> = 100.into();
}

请记住,您必须选择要创建的特定变体。对于上面的示例,我选择了

A

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