【问题标题】:generic From implementation in RustRust 中的通用 From 实现
【发布时间】:2023-01-26 21:43:16
【问题描述】:

我有两个完全相似的结构 A 和 B。我正在尝试将 A 和 B 都转换为另一种类型 C。下面给出了 A、B 和 C 的定义。

pub struct A {
   pub a: i32,
}

pub struct B {
   pub a: i32,
}

pub struct C {
   pub b: i32,
}

我从 A 转换为 C 的实现如下所示:-

impl From<A> for C { 
  fn from(a: A) -> C {
    C {b: a.a}
  }
}

由于 A 和 B 都相似,对于从 B 到 C 的转换,目前我有一个副本 上面定义的 From 的实现。

我正在寻找一种方法使 From 实现通用并且只能使用 A和B。我在这里的实现如下:-

trait Types {}

impl Types for A {}
impl Types for B {}

impl<T: Types> From<T> for C where T: Types {
    fn from(entity: T) -> C {
        C { b: entity.a }
    }
}

但是当我用上面的代码编译程序时,出现以下错误,

error[E0609]: no field `a` on type `T`
   |
27 | impl<T: Types> From<T> for C where T: Types {
   |      - type parameter 'T' declared here

我想知道解决此错误的方法,因为我别无选择,只能保留 A 和 B 并避免代码重复。

【问题讨论】:

    标签: rust traits


    【解决方案1】:

    通常这是由宏完成的:

    macro_rules! to_C {
        ($t:ty) => {
            impl From<$t> for C { 
                fn from(a: $t) -> C {
                  C{b: a.a}
                }
            }
        };
    }
    
    to_C!{A}
    to_C!{B}
    

    【讨论】:

      猜你喜欢
      • 2023-02-08
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多