Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created January 20, 2019 09:48
Show Gist options
  • Save rust-play/02c83fc52777d09d8387b1212ece37fa to your computer and use it in GitHub Desktop.
Save rust-play/02c83fc52777d09d8387b1212ece37fa to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[derive(Debug)]
struct Config {
host: String,
target: String,
port: i32,
timeout: i32,
}
impl Default for Config {
fn default() -> Self {
Self {
host: "0.0.0.0".to_string(),
target: "8.8.8.8".to_string(),
port: 0,
timeout: 1000,
}
}
}
type Builder = Box<dyn Fn(&mut Config) -> ()>;
impl Config {
fn new(v: &[Builder]) -> Self {
let mut ret = Default::default();
for c in v {
c(&mut ret)
}
ret
}
}
fn host<S>(s: S) -> Builder
where
S: Into<String>,
{
let host = s.into();
Box::new(move |config: &mut Config| config.host = host.clone())
}
fn target<S>(s: S) -> Builder
where
S: Into<String>,
{
let target = s.into();
Box::new(move |config: &mut Config| config.target = target.clone())
}
fn port(n: i32) -> Builder {
Box::new(move |config: &mut Config| config.port = n)
}
fn timeout(n: i32) -> Builder {
Box::new(move |config: &mut Config| config.timeout = n)
}
fn main() {
let config = Config::new(&[
port(25),
host("localhost"),
target("example.com"),
timeout(2000),
]);
println!("config = {:?}", config);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment