简体   繁体   English

无法为通用结构实现Into特征

[英]Unable to implement Into trait for a generic struct

I'm having trouble implementing the Into trait for a generic struct in Rust. 我在Rust中为通用结构实现Into特性时遇到了麻烦。 A simplified version of what I am trying to do is below: 我正在尝试做的简化版本如下:

struct Wrapper<T> {
    value: T
}

impl<T> Into<T> for Wrapper<T> {
    fn into(self) -> T {
        self.value
    }
}

When I try to compile, I get the following error: 当我尝试编译时,出现以下错误:

error: conflicting implementations of trait `std::convert::Into<_>` for type `Wrapper<_>`: [--explain E0119]
 --> <anon>:5:1
  |>
5 |> impl<T> Into<T> for Wrapper<T> {
  |> ^
note: conflicting implementation in crate `core`

I get the impression that the problem is the following implementation in the standard library: 我觉得问题在于标准库中的以下实现:

impl<T, U> Into<T> for U where T: From<U>

Since T might implement From<Wrapper<T>> , this might be a conflicting implementation. 由于T 可能实现From<Wrapper<T>> ,所以这可能是一个有冲突的实现。 Is there any way around this problem? 有什么办法可以解决这个问题? For example, is there a way to have an impl<T> block restricting T to types that do not implement From<Wrapper<T>> ? 例如,是否有一种方法可以使impl<T>块将T限制为不实现From<Wrapper<T>>

Actually... there isn't a way to restrict this to types T not implementing From<Wrapper<T>> . 实际上...没有办法将其限制为不实现From<Wrapper<T>>类型T Rust does not have "negative" clauses. Rust没有“ negative”子句。

Normally, the way to implement Into is simply to implement From and get Into for free . 通常,实现Into的方法就是简单地实现From免费获取Into However, in your case the implementation would be: 但是,在您的情况下,实现将是:

impl<T> From<Wrapper<T>> for T {
    fn from(w: Wrapper<T>) -> T { w.value }
}

and this runs into the orphan rules. 这碰到了孤立规则。 You are not allowed to implement From for all T . 不允许对所有T实施From

There might be a trick, but I cannot see it here. 可能有一个窍门,但我在这里看不到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM