"ToOwnedBox": possible solutions?


I’m currently working on an API that would benefit from having a Borrow alternative that uses boxed slices as the owned target rather than vectors. (So &[T] => Box<[T]>, &str => Box<str>, AlreadyOwned => AlreadyOwned, with the possibility of probably into_boxed_sliceing String and Vec.)

Basically, I want to make a mapping that stores immutable values, so I don’t need to pay for the grow ability of String/Vec. Is there a way to do this that doesn’t provide special wrappers or entry points for these types? (Ideally, it’d work for any 'static data and its borrowed format, not just those defined in std.)


Why can you do slice.to_vec().into_boxed_slice() or string.to_string().into_boxed_str()? When you use to_vec or to_string it only allocates as much memory as needed to store the slice or str

You could create a trait to do this

trait ToBoxed {
    fn to_boxed(&self) -> Box<Self>;

impl<T: Clone> ToBoxed for [T] {
    fn to_boxed(&self) -> Box<Self> {

impl ToBoxed for str {
    fn to_boxed(&self) -> Box<Self> {



I… expected it to be more complicated than that.

Just add a type Boxed and a impl<T: Clone> { type Boxed=T; }, and you’ve got the perfect ToOwned variant (modulo other people’s ToOwned implementations, but that’s a reasonable limitation, I guess).