How to abstract over a reference to a value or a value itself?

后端 未结 1 1607
时光取名叫无心
时光取名叫无心 2020-11-30 14:18

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 {
          


        
相关标签:
1条回答
  • 2020-11-30 15:04

    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.

    0 讨论(0)
提交回复
热议问题