How to create a slice with a single element?


#1

Problem: I have &T and I want a slice with a single element &[T]. It looks like this should be possible, because T and [T; 1] have exactly the same representation. But how should I actually do this?

I’ve come up with the following implementation:

fn singleton_slice<T>(x: &T) -> &[T] {
    unsafe { ::std::slice::from_raw_parts(x as *const T, 1) }
}

Is it correct? If there perhaps a safe way to do this?


#2

To put a question in context, in Cargo I need to create a &[String] while I have Option<String>. I currently allocate a vector for this, and it does not feel neat: https://github.com/rust-lang/cargo/pull/3691/files#diff-e8dd5a998d18e725fd09815c4f276c47R81.


#3

You’re looking for this crate: https://github.com/steveklabnik/ref_slice