Advertisement
NLinker

Partial specialization for generic struct

Nov 21st, 2019
975
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.90 KB | None | 0 0
  1. // https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9300ded73faa7558e442173adeaee592
  2.  
  3. use std::fmt::Debug;
  4. use rand::{Rng, thread_rng};
  5. use rand::prelude::ThreadRng;
  6. use std::marker::PhantomData;
  7.  
  8. //              Так    vvvvvvvvv      vvvvvvvvvvvvvvvvvvvvvvvvvv
  9. struct MyStruct<D, R = ThreadRng, F = &'static dyn Fn(&D)-> bool> {
  10.    f: F,
  11.    rng: R,
  12.    _s: PhantomData<D>,
  13. }
  14.  
  15. trait Call<D: Debug> {
  16.    fn call(&self, d: D) -> Option<D>;
  17. }
  18.  
  19. impl<D, R, F> Call<D> for MyStruct<D, R, F>
  20.    where D: Debug,
  21.         R: Rng,
  22.         F: Fn(&D) -> bool,
  23. {
  24.    fn call(&self, d: D) -> Option<D> {
  25.        if (self.f)(&d) { Some(d) } else { None }
  26.    }
  27. }
  28.  
  29. impl<D, R, F> MyStruct<D, R, F>
  30. where D: Debug,
  31.      R: Rng,
  32.      F: Fn(&D) -> bool,
  33. {
  34.    fn with_f_r(f: F, rng: R) -> Self {
  35.        MyStruct { f, rng, _s: PhantomData }
  36.    }
  37. }
  38.  
  39. impl<D, F> MyStruct<D, ThreadRng, F>
  40. where D: Debug,
  41.      F: Fn(&D) -> bool,
  42. {
  43.    fn with_f(f: F) -> Self {
  44.        let rng = thread_rng();
  45.        MyStruct { f, rng, _s: PhantomData }
  46.    }
  47. }
  48.  
  49. impl<D> MyStruct<D, ThreadRng, &dyn Fn(&D)->bool>
  50. where D: Debug
  51. {
  52.    fn new() -> Self {
  53.        let f = &|_: & D| false;
  54.        let rng = thread_rng();
  55.        MyStruct { f, rng, _s: PhantomData }
  56.    }
  57. }
  58.  
  59. // Или так
  60. fn my_struct_new<D: Debug>() -> MyStruct<D, ThreadRng, &'static dyn Fn(&D)->bool> {
  61.     let f = &|_: & D| false;
  62.     let rng = thread_rng();
  63.     MyStruct { f, rng, _s: PhantomData }
  64. }
  65.  
  66.  
  67. fn main() {
  68.     let m1 = MyStruct::<()>::new();
  69.     println!("{:?}", m1.call(()));
  70.     let m1prime = my_struct_new::<()>();
  71.     println!("{:?}", m1prime.call(()));
  72.  
  73.     let f2 = |_: &()| true;
  74.     let m2 = MyStruct::with_f(f2);
  75.     println!("{:?}", m2.call(()));
  76.  
  77.     let f3 = |_: &()| true;
  78.     let r3 = thread_rng();
  79.     let m3 = MyStruct::with_f_r(f3, r3);
  80.     println!("{:?}", m3.call(()));
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement