Return new vec or slice

Is there a built-in way to express the idea of returning either a newly created Vec or a slice of the same type?

I'm thinking kinda like a Result or Either but where one variant is the Owned version and the other is Borrowed

Example playground - looking for something like DataWrapper here:

use std::fmt::{Display, Debug, Formatter};

enum DataWrapper<'a, T> {
    Owned(Vec<T>),
    Borrowed(&'a [T])
}

impl <'a, T: Debug> Display for DataWrapper<'a, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Owned(v) => write!(f, "{:?} (owned)", v),
            Self::Borrowed(v) => write!(f, "{:?} (borrowed)", v),
        }
    }
}


fn get_something<'a> (update_immutably:bool, input:&'a [u8]) -> DataWrapper<'a, u8> {
    if update_immutably {
        let mut data = input.to_vec();
        data[1] = 42;
        DataWrapper::Owned(data)
    } else {
        DataWrapper::Borrowed(input)
    }
}

fn main() {
    let foo = vec![1,3,7];
    
    println!("{}", get_something(false, &foo)); //[1, 3, 7] (borrowed)
    println!("{}", get_something(true, &foo)); //[1, 42, 7] (owned)
    
}
1 Like

That's std::borrow::Cow<[T]>.

3 Likes

Ah... seen people talk enthusiastically about it before but didn't know I needed it. Cool stuff!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.