Option<&mut V> == Option<& V> for V: Eq

For V: Eq, is there an easy way to compare a

x: Option<&mut V>;
y: Option<& V>;

I know that I can do this by destructuring x & y, but am wondering if there is a more idiomatic way.

How about x.as_deref() == y?

2 Likes

I'm confused.

Do you want to check that the two references are equal in that they refer to the very same vector?

Or do you want to check that two vectors have the same content?

If the former, surely one cannot even create mutable and immutable reference to the same thing?
For example:

    type V = Vec<i8>;

    let mut vx: V = vec![1,2,3];
    let vy: V = vec![4,5,6];

    let x = Some(&mut vx);    // An Option<&mut V>
    let y = Some(& vx);           // An Option<& V>

produces:

error[E0502]: cannot borrow `vx` as immutable because it is also borrowed as mutable
   --> src/bin/conq_ws_server.rs:200:18
    |
199 |     let x = Some(&mut vx);    // An Option<&mut V>
    |                  ------- mutable borrow occurs here
200 |     let y = Some(& vx);           // An Option<& V>
    |                  ^^^^ immutable borrow occurs here
201 |
202 |     if x.as_deref() == y {
    |        - mutable borrow later used here
1 Like

Probably OP means structural/deep/by-value equality, because the post starts by assuming that V: Eq.

1 Like

I assume they mean the same as you get when comparing Option<&T> to Option<&T>, that is, to compare whether the values are equal. Indeed as you say, mutable references are guaranteed to be unique, so if they meant the other thing, they can shorten the condition to false.

1 Like

Okey, dokey.

1 Like

@ZiCog: Valid question. Thanks for bringing it up.

@alice , @H2CO3 : Yes, by-value equally is what I had in mind.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.