Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. use num_traits::PrimInt;
  2.  
  3. /// this only exists to be able to instantiate the value via `Default::default()`.
  4. /// It could, however, be useful for adding other methods too.
  5. trait MyPrimInt: PrimInt + Default {}
  6.  
  7. macro_rules! impl_my_prim_int {
  8. ($($ty:ident)*) => ($(impl MyPrimInt for $ty {})*)
  9. }
  10.  
  11. impl_my_prim_int! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
  12.  
  13. trait MakeOne {
  14. fn make_one() -> Self;
  15. }
  16.  
  17. impl MakeOne for String {
  18. fn make_one() -> Self {
  19. String::new()
  20. }
  21. }
  22.  
  23. impl<T: MyPrimInt> MakeOne for T {
  24. fn make_one() -> Self {
  25. Default::default()
  26. }
  27. }
  28.  
  29. #[derive(Debug)]
  30. struct TheStruct<T> {
  31. val: T,
  32. }
  33.  
  34. impl<T: MakeOne> TheStruct<T> {
  35. fn new() -> Self {
  36. TheStruct {
  37. val: T::make_one()
  38. }
  39. }
  40. }
  41.  
  42. fn main() {
  43. let str = TheStruct::<String>::new();
  44. println!("str = {:?}", str);
  45.  
  46. let int = TheStruct::<i16>::new();
  47. println!("int = {:?}", int);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement