Advertisement
umuro

data_or_ref.rs

Mar 31st, 2023
1,447
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.08 KB | Software | 0 0
  1. use std::rc::Rc;
  2.  
  3. enum DataOrRef<'a, T> {
  4.    Owned(T),
  5.    Borrowed(&'a T),
  6. }
  7.  
  8. struct MyStruct<'a, T> {
  9.    data: DataOrRef<'a, T>,
  10. }
  11.  
  12. impl<'a, T> MyStruct<'a, T> {
  13.     fn new_owned(data: T) -> Self {
  14.         MyStruct {
  15.             data: DataOrRef::Owned(data),
  16.         }
  17.     }
  18.  
  19.     fn new_borrowed(data: &'a T) -> Self {
  20.        MyStruct {
  21.            data: DataOrRef::Borrowed(data),
  22.        }
  23.    }
  24.  
  25.    fn as_ref(&self) -> &T {
  26.        match &self.data {
  27.            DataOrRef::Owned(d) => &d,
  28.            DataOrRef::Borrowed(d) => d,
  29.        }
  30.    }
  31.  
  32.    fn clone(&self) -> Self
  33.    where
  34.        T: Clone,
  35.    {
  36.        match &self.data {
  37.            DataOrRef::Owned(d) => MyStruct::new_owned(d.clone()),
  38.            DataOrRef::Borrowed(d) => MyStruct::new_borrowed(d),
  39.        }
  40.    }
  41.  
  42.    fn to_owned(&self) -> MyStruct<'static, T>
  43.     where
  44.         T: Clone,
  45.     {
  46.         match &self.data {
  47.             DataOrRef::Owned(d) => MyStruct::new_owned(d.clone()),
  48.             DataOrRef::Borrowed(d) => MyStruct::new_owned(d.clone()),
  49.         }
  50.     }
  51. }
  52.  
Tags: optimization
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement