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 {
I suggest you use a Cow
, since your BorrowedOrOwned
has no difference to Cow
except that it has fewer convenience methods. Anybody that gets a hold of a BorrowedOrOwned
object could match on it and get the owned value or a mutable reference to it. If you want to prevent the confusion of being able to get a mutable reference or the object itself, the solution below applies, too.
For your use case i'd simply stay with &T
, since there's no reason to make the API more complex. If a user wants a usize
, when T
is usize
, they can simply dereference the reference.
An owned object only makes sense, if you expect the user to actually process it in an owned fashion. And even then, Cow
is meant to abstract over big/heavy objects that you pass by ownership for the purpose of not requiring anyone to clone
it. Your use case is the opposite, you want to pass small objects by ownership to prevent users from needing to copy small objects, and instead you are copying it.