daily pastebin goal
42%
SHARE
TWEET

Untitled

a guest Jan 20th, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #[derive(Debug)]
  2. struct Server {
  3.     host: String,
  4.     target: String,
  5.     port: i32,
  6.     timeout: i32,
  7. }
  8.  
  9. impl Default for Server  {
  10.     fn default() -> Self {
  11.         Self {
  12.             host: "0.0.0.0".to_string(),
  13.             target: "8.8.8.8".to_string(),
  14.             port: 0,
  15.             timeout: 1000,
  16.         }
  17.     }
  18. }
  19.  
  20. trait Builder {
  21.     type Config : Default;
  22.    
  23.     fn build(v: &[BuilderFn<Self::Config>]) -> Self::Config {
  24.         let mut ret = Default::default();
  25.         for c in v {
  26.             c(&mut ret)
  27.         }
  28.         ret
  29.     }    
  30. }
  31.  
  32. type BuilderFn<T> = Box<dyn Fn(&mut T) -> ()>;
  33.  
  34.  
  35. impl Builder for Server {
  36.     type Config = Self;
  37. }
  38.  
  39. fn host<S>(s: S) -> BuilderFn<Server>
  40. where
  41.     S: Into<String>,
  42. {
  43.     let host = s.into();
  44.     Box::new(move |config: &mut Server| config.host = host.clone())
  45. }
  46.  
  47. fn target<S>(s: S) -> BuilderFn<Server>
  48. where
  49.     S: Into<String>,
  50. {
  51.     let target = s.into();
  52.     Box::new(move |config: &mut Server| config.target = target.clone())
  53. }
  54.  
  55. fn port(n: i32) -> BuilderFn<Server> {
  56.     Box::new(move |config: &mut Server| config.port = n)
  57. }
  58.  
  59. fn timeout(n: i32) -> BuilderFn<Server> {
  60.     Box::new(move |config: &mut Server| config.timeout = n)
  61. }
  62.  
  63. fn main() {
  64.     let server = Server::build(&[
  65.         port(25),
  66.         host("localhost"),
  67.         target("example.com"),
  68.         timeout(2000),
  69.     ]);
  70.     println!("server  = {:?}", server);
  71. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top