1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#![allow(dead_code)]
#![allow(unused_variables)]
use std::{cell::RefCell, ops::Deref};
use std::rc::Rc;

pub struct Builder<T> {
    inner: RefCell<Option<Rc<T>>>,
}

impl<T> Default for Builder<T>
where
    T: Default + Clone,
{
    fn default() -> Self {
        Self {
            inner: RefCell::new(Some(Rc::new(Default::default()))),
        }
    }
}

impl<T> Builder<T>
where
    T: Default + Clone,
{
    pub fn build(&self) -> Option<T> {
        let mut inner = self.inner.borrow_mut();
        match inner.as_ref() {
            Some(val) => {
                let ret = val.clone();
                *inner = None;
                Some((*ret).clone())
            }
            None => None,
        }
    }
}

pub trait Construction<T> {
    fn construct() -> Builder<T>;
}

impl<T> Construction<T> for T
where
    T: Default + Clone,
{
    fn construct() -> Builder<T> {
        Builder::<T>::default()
    }
}

// #[derive(Default, Copy, Clone)]
// pub struct Button;

// impl Builder<Button> {
//     pub fn title(&self, _: &str) -> &Self {
//         self
//     }

//     pub fn background(&self, _: &str) -> &Self {
//         self
//     }

//     pub fn enabled(&self, _: bool) -> &Self {
//         self
//     }
// }

// fn main() {
//     let a = Builder::<Button>::default()
//         .title("My button")
//         .background("#FF0044")
//         .enabled(true)
//         .build().unwrap_or_default(); // OUCH
//         // .build().expect("The chest is empty"); // Specify message
//         // .build().unwrap(); // Just panic
// }