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

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.


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
}

Tags:

Rust