Timmmm
Timmmm

Reputation: 96828

Rust compare Option<Vec<u8>> with Option<&[u8]>

Is there an elegant way to compare Option<Vec<u8>> for equality with Option<&[u8]>? (Or equivalently with Result instead of Option.)

Upvotes: 9

Views: 2801

Answers (2)

Stargateur
Stargateur

Reputation: 26757

You just need to convert Option<Vec<u8>> to Option<&[u8]>, using as_ref() and Index trait:

fn foo(a: Option<Vec<u8>>, b: Option<&[u8]>) -> bool {
    a.as_ref().map(|x| &x[..]) == b
}

As of Rust 1.40, you can use as_deref():

fn foo(a: Option<Vec<u8>>, b: Option<&[u8]>) -> bool {
    a.as_deref() == b
}

Upvotes: 11

Cerberus
Cerberus

Reputation: 10247

Maybe it's suboptimal, but this code seems to compile:

fn cmp(first: Option<Vec<u8>>, second: Option<&[u8]>) -> bool {
    first.as_ref().map(Vec::as_ref) == second
}

Playground

There are two key transformations here:

  1. The first Option holds the owned value, the second - a reference. So we should go from Option<T> (or &Option<T>) to Option<&T>, and this is achieved using the as_ref method of Option.

  2. The first Option now holds &Vec<u8>, and we're going to compare it to &[u8]. This is handled again by the as_ref method, now defined on the AsRef<[u8]> trait and implemented on Vec.

Upvotes: 12

Related Questions