Is there an elegant way to compare Option<Vec<u8>>
for equality with Option<&[u8]>
? (Or equivalently with Result
instead of Option
.)
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>
) to Option<&T>
, and this is achieved using the as_ref
method of Option
.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With