I have an Option in Rust, and I need to use it in a function that accepts a slice. How do I get a slice from an Option where Some(x)'s slice has one element and None's has zero elements?
I have an Option in Rust, and I need to use it in a function that accepts a slice. How do I get a slice from an Option where Some(x)'s slice has one element and None's has zero elements?
This will produce an immutable slice of an Option:
the_option.as_ref()
.map(core::slice::from_ref)
.unwrap_or_default()
This will produce a mutable slice of an Option:
the_mutable_option.as_mut()
.map(core::slice::from_mut)
.unwrap_or_default()
These first use Option's as_ref or as_mut method to produce a second Option that contains a reference to the value still inside the original Option.
Then, they use Option's map method, which, if the second Option is a Some value, applies core::slice::from_ref or core::slice::from_mut to the reference inside the Some value, changing it to a one-element slice.
Then, it consumes the second Option using Option's unwrap_or_default method. If it's a Some value, the one-element slice from the previous step is produced. Otherwise, if it's a None value, the default slice is produced, which is an empty slice.
You can use the two functions: opt_slice and opt_slice_mut, provided by the crate ref_slice
pub fn opt_slice<A>(opt: &Option<A>) -> &[A]
pub fn opt_slice_mut<A>(opt: &mut Option<A>) -> &mut [A]
Option supports IntoIterator, so
let v = opt.into_iter().collect::<Vec<_>>()
gives you a Vec containing either 0 or 1 elements, which can be passed to your function because Vec<T> implements Deref<T>.