19

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?

3 Answers 3

23

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.

1
  • 2
    .map_or_else() can be replaced by .map(core::slice::from{ref|mut}).unwrap_or_default(). Dec 30, 2021 at 2:35
9

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]
-1

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>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.