I have two types that can be tested for equality. However, once I wrap them in Option
s, the nicety provided by various PartialEq
implementations goes right out the window. I have to use map
or otherwise convert them.
As an example, let's use &str
and String
:
fn main() {
let a = "hello";
let b = "hello".to_owned();
assert_eq!(a, b); // Just fine
let a = Some(a);
let b = Some(b);
// error: mismatched types
assert_eq!(a, b);
// error: mismatched types
assert_eq!(a, b.as_ref());
// works, but highly tied to strings or slices,
// requires me to remember which is which
assert_eq!(a, b.as_ref().map(|x| &x[..]));
}
There surely must be a simpler or more straight-forward way to do this?
Side-question — what prevents Option
from implementing PartialEq
a bit more broadly? I'm guessing coherence, my old nemesis.
impl<T, U> PartialEq<Option<U>> for Option<T>
where
T: PartialEq<U>,
There's some chatter about this in the RFCs and Rust issues (1, 2).
As of Rust 1.40, you can use as_deref()
so you don't have to remember what is what:
assert_eq!(a.as_deref(), b.as_deref());
Before Rust 1.40, I would do something like this:
match (&a, &b) {
(Some(a), Some(b)) => assert_eq!(a, b),
(None, None) => (),
_ => panic!("a and b not equal"),
}
Another option is a custom assertion, based on assert_eq!
:
macro_rules! cmp_eq_option {
($left:expr, $right:expr) => {{
match (&$left, &$right) {
(Some(left_val), Some(right_val)) => *left_val == *right_val,
(None, None) => true,
_ => false,
}
}};
}
#[macro_export]
macro_rules! assert_eq_option {
($left:expr, $right:expr) => ({
if !cmp_eq_option!($left, $right) {
panic!(r#"assertion failed: `(left == right)`
left: `{:?}`,
right: `{:?}`"#, $left, $right)
}
});
($left:expr, $right:expr,) => ({
assert_eq_option!($left, $right)
});
($left:expr, $right:expr, $($arg:tt)+) => ({
if !cmp_eq_option!($left, $right) {
panic!(r#"assertion failed: `(left == right)`
left: `{:?}`,
right: `{:?}`: {}"#, $left, $right, format_args!($($arg)+))
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With