I have some structs which could either be given a mutable slice or a Vec
to own. The best solution I've been able to come up with is to make a simple enum which can contain a slice or a Vec
and then Deref
s to a slice.
pub enum DataSource<'a, T> {
Borrowed(&'a mut [T]),
Owned(Vec<T>),
}
impl<T> Deref for DataSource<'_, T> {
type Target = [T];
fn deref(&self) -> &Self::Target {
match self {
DataSource::Borrowed(val) => val,
DataSource::Owned(val) => val,
}
}
}
impl<T> DerefMut for DataSource<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
DataSource::Borrowed(val) => val,
DataSource::Owned(val) => val,
}
}
}
This seems quite simple (even if it's not recommended to implement Deref
for your own types) so I'm sure I'm not the first person to think of this.
Is there something like this already in the Rust std library, or is there a crate which provides it?