Stream: t-libs

Topic: comparing Some(T) with T


Elichai Turkel (Jan 21 2020 at 16:12, on Zulip):

Hi,
How do people feel about adding something like impl<T: PartialEq> PartialEq<Option<T>> for T such that Some(5) == 5?

I can PR this but wanted to know if people even want that.
I think it helps ergonomics, especially in tests.

bstrie (Jan 21 2020 at 16:19, on Zulip):

I'd say it's worth discussing, but my gut is that people will be naturally wary of it. is there any sort of precedent for this behavior anywhere else in the stdlib?

Elichai Turkel (Jan 21 2020 at 16:52, on Zulip):

I'd say it's worth discussing, but my gut is that people will be naturally wary of it. is there any sort of precedent for this behavior anywhere else in the stdlib?

Yes. IpAddr(Ipv4Addr) == Ipv4Addr it's not exactly the same because there are no user defined generics here, but close enough IMHO

ecstatic-morse (Jan 21 2020 at 18:44, on Zulip):

How would this feel when comparing an Option<Option<T>> with None?

Simon Sapin (Jan 21 2020 at 19:06, on Zulip):

Arguably an IP address that happens to be of v4 variant is an IPv4 address

Simon Sapin (Jan 21 2020 at 19:07, on Zulip):

But Option is often used where optionalness is significant

Elichai Turkel (Jan 23 2020 at 10:40, on Zulip):

How would this feel when comparing an Option<Option<T>> with None?

Well that's a great point. sadly I think that point is more than enough to scrap the idea.

XAMPPRocky (Jan 23 2020 at 10:58, on Zulip):

I still think there's some merit, not as syntax with == but with a method like option.deep_eq(foo) or something, as in my experience option.map_or(false, |x| x == y) is a pretty common pattern when dealing with options.

Simon Sapin (Jan 23 2020 at 12:38, on Zulip):

The Option<Option<T>> case also means you might hit trait coherence errors when implementing something like this

XAMPPRocky (Jan 23 2020 at 12:53, on Zulip):

@Simon Sapin Even in this case?

impl<T> Option<T> {
    fn deep_eq(&self, rhs: T) -> bool {
        self.map_or(false, |lhs| lhs == rhs)
    }
}
Simon Sapin (Jan 23 2020 at 12:57, on Zulip):

That one looks probably fine because it only accepts T as a parameter. I meant for something that wants to accept either T or Option<T>, but even then it depends on the exact formulation

cuviper (Jan 23 2020 at 15:31, on Zulip):

How would this feel when comparing an Option<Option<T>> with None?

Wouldn't this just be a type inference issue? Once you clarify None::<T> or None::<Option<T>>, it should be fine.

cuviper (Jan 23 2020 at 15:33, on Zulip):

But the new blanket impl does seem like a breaking change anyway

Last update: Feb 25 2020 at 04:25UTC