Rust Builder Pattern
Revision History
No revision history recorded yet.
#[derive(Debug)]
pub struct Request {
pub url: String,
pub method: String,
pub body: Option<String>,
pub timeout: u32,
}
#[derive(Default)]
pub struct RequestBuilder {
url: String,
method: String,
body: Option<String>,
timeout: u32,
}
impl RequestBuilder {
pub fn new(url: impl Into<String>) -> Self {
Self {
url: url.into(),
method: "GET".into(),
timeout: 30,
..Default::default()
}
}
pub fn method(mut self, m: impl Into<String>) -> Self {
self.method = m.into(); self
}
pub fn body(mut self, b: impl Into<String>) -> Self {
self.body = Some(b.into()); self
}
pub fn timeout(mut self, secs: u32) -> Self {
self.timeout = secs; self
}
pub fn build(self) -> Request {
Request {
url: self.url,
method: self.method,
body: self.body,
timeout: self.timeout,
}
}
}