Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9300ded73faa7558e442173adeaee592
- use std::fmt::Debug;
- use rand::{Rng, thread_rng};
- use rand::prelude::ThreadRng;
- use std::marker::PhantomData;
- // Так vvvvvvvvv vvvvvvvvvvvvvvvvvvvvvvvvvv
- struct MyStruct<D, R = ThreadRng, F = &'static dyn Fn(&D)-> bool> {
- f: F,
- rng: R,
- _s: PhantomData<D>,
- }
- trait Call<D: Debug> {
- fn call(&self, d: D) -> Option<D>;
- }
- impl<D, R, F> Call<D> for MyStruct<D, R, F>
- where D: Debug,
- R: Rng,
- F: Fn(&D) -> bool,
- {
- fn call(&self, d: D) -> Option<D> {
- if (self.f)(&d) { Some(d) } else { None }
- }
- }
- impl<D, R, F> MyStruct<D, R, F>
- where D: Debug,
- R: Rng,
- F: Fn(&D) -> bool,
- {
- fn with_f_r(f: F, rng: R) -> Self {
- MyStruct { f, rng, _s: PhantomData }
- }
- }
- impl<D, F> MyStruct<D, ThreadRng, F>
- where D: Debug,
- F: Fn(&D) -> bool,
- {
- fn with_f(f: F) -> Self {
- let rng = thread_rng();
- MyStruct { f, rng, _s: PhantomData }
- }
- }
- impl<D> MyStruct<D, ThreadRng, &dyn Fn(&D)->bool>
- where D: Debug
- {
- fn new() -> Self {
- let f = &|_: & D| false;
- let rng = thread_rng();
- MyStruct { f, rng, _s: PhantomData }
- }
- }
- // Или так
- fn my_struct_new<D: Debug>() -> MyStruct<D, ThreadRng, &'static dyn Fn(&D)->bool> {
- let f = &|_: & D| false;
- let rng = thread_rng();
- MyStruct { f, rng, _s: PhantomData }
- }
- fn main() {
- let m1 = MyStruct::<()>::new();
- println!("{:?}", m1.call(()));
- let m1prime = my_struct_new::<()>();
- println!("{:?}", m1prime.call(()));
- let f2 = |_: &()| true;
- let m2 = MyStruct::with_f(f2);
- println!("{:?}", m2.call(()));
- let f3 = |_: &()| true;
- let r3 = thread_rng();
- let m3 = MyStruct::with_f_r(f3, r3);
- println!("{:?}", m3.call(()));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement