当 PartialEq 的实现不合适时,如何断言两个变量相等?

Pam*_*sse 3 unit-testing traits rust

在我的程序中,我用以下结构表示“事件”:

struct Event {
    value: &'static str,
    timestamp: usize,
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我曾经PartialEq比较Event变量:大多数时候,Event如果两个相同,我认为它们相等value

impl PartialEq for Event {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_loose_equality() {
        let a = Event { value: "a-value", timestamp: 12345 };
        let b = Event { value: "a-value", timestamp: 23456 };

        assert_eq!(a, b);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,在某些测试中,我想确保两个这样的变量“严格相等”:测试应该失败,它们有不同timestamp(在方面不同Eq)。

根据以下文档assert_eq!

断言两个表达式彼此相等(使用 PartialEq)。 来源

所以,我正在寻找一个Eq等价的、assert_Eq_eq!类似的。

(或者我是否误解了如何Eq工作以及应该使用?)

这是我未能完成的:

impl Eq for Event {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_strict_equality() {
        let a = Event { value: "a-value", timestamp: 12345 };
        let b = Event { value: "a-value", timestamp: 12345 };

        // ???
    }
}
Run Code Online (Sandbox Code Playgroud)

She*_*ter 5

我将创建适当类型的“视图”:

struct Event {
    value: &'static str,
    timestamp: usize,
}

#[derive(Debug, PartialEq)]
struct Exact<'a> {
    value: &'a &'static str,
    timestamp: &'a usize,
}

impl Event {
    fn exact(&self) -> Exact<'_> {
        let Self { value, timestamp } = self;
        Exact { value, timestamp }
    }
}

fn demo(a: Event, b: Event) {
    assert_eq!(a.exact(), b.exact());
}
Run Code Online (Sandbox Code Playgroud)

在这里,我选择引用每个字段来演示一般情况,但您不需要此特定示例的引用(&str并且usize实现Copy和很小)。

PartialEq您还可以选择根本不在原始类型上实现,而通过视图进行比较:

struct Event {
    value: &'static str,
    timestamp: usize,
}

#[derive(Debug, PartialEq)]
struct Exact<'a> {
    value: &'a &'static str,
    timestamp: &'a usize,
}

impl Event {
    fn exact(&self) -> Exact<'_> {
        let Self { value, timestamp } = self;
        Exact { value, timestamp }
    }
}

fn demo(a: Event, b: Event) {
    assert_eq!(a.exact(), b.exact());
}
Run Code Online (Sandbox Code Playgroud)