Search code examples
rustslice

How can I get a slice from an Option in Rust?


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?


Solution

  • Rust 1.75 and later

    Option now has as_slice and as_mut_slice methods in the standard library.

    Prior to Rust 1.75

    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.