首页 > 解决方案 > 使用 PhantomData 时无法按预期推导出 PartialEq

问题描述

我正在尝试制作自己的自定义类型指针,但似乎无法使其具有可比性。我将我的代码缩小到这个:

use std::marker::PhantomData;

#[derive(PartialEq, Copy, Clone)]
pub struct PhantomPair<PHANTOM, REAL: Copy + Clone + PartialEq> {
    real: REAL,
    phantom: PhantomData<PHANTOM>,
}

impl<PHANTOM, REAL: Copy + Clone + PartialEq> PhantomPair<PHANTOM, REAL> {
    pub fn new(data: REAL) -> Self {
        PhantomPair {
            real: data,
            phantom: PhantomData,
        }
    }
}

fn is_eq<PHANTOM, REAL: Copy + Clone + PartialEq>(
    a: PhantomPair<PHANTOM, REAL>,
    b: PhantomPair<PHANTOM, REAL>,
) -> bool {
    a == b
}

fn main() {}

编译器给出以下错误:

error[E0369]: binary operation `==` cannot be applied to type `PhantomPair<PHANTOM, REAL>`
  --> src/main.rs:22:5
   |
22 |     a == b
   |     ^^^^^^
   |
   = note: an implementation of `std::cmp::PartialEq` might be missing for `PhantomPair<PHANTOM, REAL>`

我希望PhantomPair有一个PartialEq使用REAL's的派生PartialEq。据我所知,PhantomDataPartialEq基本上实现了假设平等。

当我尝试添加PartialOrdto#[derive]和 toREAL的约束时,也会发生同样的问题。

标签: rusttraits

解决方案


推荐阅读