I have a trait that defines an interface for objects that can hold a value. The trait has a way of getting the current value:
pub trait HasValue<T> {
fn get_current_value(&self) -> &T;
}
This is fine, but I realized that depending on the actual implementation, sometimes it's convenient to return a reference if T
is stored in a field, and sometimes it's convenient to return a clone of T
if the backing field was being shared across threads (for example). I'm struggling to figure out how to represent this in the trait. I could have something like this:
pub enum BorrowedOrOwned<'a, T: 'a> {
Borrowed(&'a T),
Owned(T)
}
impl<'a, T: 'a> Deref for BorrowedOrOwned<'a, T> {
type Target = T;
fn deref(&self) -> &T {
use self::BorrowedOrOwned::*;
match self {
&Borrowed(b) => b,
&Owned(ref o) => o,
}
}
}
And change get_current_value()
to return a BorrowedOrOwned<T>
but I'm not sure that this is idiomatic. BorrowedOrOwned<T>
kind of reminds me of Cow<T>
but since the point of Cow
is to copy-on-write and I will be discarding any writes, that seems semantically wrong.
Is Cow<T>
the correct way to abstract over a reference or an owned value? Is there a better way than BorrowedOrOwned<T>
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…