How to create a slice with a single element?

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?


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:

For the benefit of people googling that page — this has been added to the stdlib: