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:
The first Option holds the owned value, the second - a reference. So we should go from
Option<T>
(or&Option<T>
) toOption<&T>
, and this is achieved using theas_ref
method ofOption
.The first
Option
now holds&Vec<u8>
, and we're going to compare it to&[u8]
. This is handled again by theas_ref
method, now defined on theAsRef<[u8]>
trait and implemented onVec
.
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
}