繁体   English   中英

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

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

我在Rust中为通用结构实现Into特性时遇到了麻烦。 我正在尝试做的简化版本如下:

struct Wrapper<T> {
    value: T
}

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

当我尝试编译时,出现以下错误:

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`

我觉得问题在于标准库中的以下实现:

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

由于T 可能实现From<Wrapper<T>> ,所以这可能是一个有冲突的实现。 有什么办法可以解决这个问题? 例如,是否有一种方法可以使impl<T>块将T限制为不实现From<Wrapper<T>>

实际上...没有办法将其限制为不实现From<Wrapper<T>>类型T Rust没有“ negative”子句。

通常,实现Into的方法就是简单地实现From免费获取Into 但是,在您的情况下,实现将是:

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

这碰到了孤立规则。 不允许对所有T实施From

可能有一个窍门,但我在这里看不到。

暂无
暂无

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

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