所有实现了 Into<A> 的类型都可以实现 Into<B> 约束。

3

我想实现一个转换特性,它能覆盖所有已经存在的支持转换的类型。我认为可以按照以下方式完成:

impl<T> Into<B> for T
where
    T: Into<A>,
{
  fn into(self) -> B {
    let a: A = self.into();
    B::CaseA(a)
  }
}

然而编译器会抛出以下错误:

error[E0119]: conflicting implementations of trait `std::convert::Into<block::ItemContent>`
   --> yrs\src\block.rs:945:1
    |
945 | / impl<T> Into<B> for T
946 | | where
947 | |     T: Into<A>,
948 | | {
...   |
952 | |     }
953 | | }
    | |_^
    |
    = note: conflicting implementation in crate `core`:
            - impl<T, U> Into<U> for T
              where U: From<T>;

error[E0210]: type parameter `T` must be covered by another type when it appears before the first local type (`B`)
   --> yrs\src\block.rs:945:6
    |
945 | impl<T> Into<B> for T
    |      ^ type parameter `T` must be covered by another type when it appears before the first local type (`B`)
    |
    = note: 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
    = note: in this case, 'before' refers to the following order: `impl<..> ForeignTrait<T1, ..., Tn> for T0`, where `T0` is the first and `Tn` is the last

这是否可能实现?我正在寻找一种自动扩展对所有实例的新类型转换的方式,以支持转换为另一种现有类型。


1
你的箱子里定义了 B 吗?如果是这样,你可以实现 From<T> for B 而不是 Into<B> for Timpl<T> From<T> for B where T: Into<A> { fn from(t: T) -> Self { let a: A = t.into(); B::CaseA(a) } }。这样你就自动获得了 FromInto。- https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=15772767b7de0fa2ccb1cb5166ab4aeb - user4815162342
1个回答

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接