Hi there,
I am writing a struct that will wrap a value that cannot be cloneable (e.g. a database connection). I looked for similar examples of what I am trying to achieve but in all cases the wrapped value is cloneable and the Cow smart pointer is used. I couldn't find any smarter pointer that would satisfy my use case, so I am using something along the lines of the following code:
enum Either<'a, T> { Owned(T), Borrowed(&'a T) }
#[derive(Debug)]
pub struct NonCloneableValue;
pub struct Wrapper<'a>(Either<'a, NonCloneableValue>);
impl <'a> Wrapper<'a> {
pub fn from_borrowed(v: &'a NonCloneableValue) -> Wrapper<'a> {
Wrapper(Either::Borrowed(v))
}
pub fn from_owned(v: NonCloneableValue) -> Wrapper<'static> {
Wrapper(Either::Owned(v))
}
/// Gets a reference to the value.
pub fn get_value(&self) -> &NonCloneableValue {
match &self.0 {
Either::Owned(v) => &v,
Either::Borrowed(v) => v,
}
}
}
The code is available at the Rust Playground.
I would like to ask if there is a more idiomatic way in Rust for the code I wrote above, perhaps some existing std struct or library I am not aware of.
Many thanks for your time!