Builder pattern in rust
This is a short scratch of the builder pattern implemented in rust. In this example we are building a url with different query parameters.
use std::collections::HashMap;
struct UrlBuilder {
queries: HashMap<String, String>,
base_url: String
}
impl UrlBuilder {
pub fn new(base_url: &str) -> Self{
Self {base_url: String::from(base_url), queries: HashMap::new()}
}
pub fn as_string(&self) -> String {
let mut query_string = String::new();
for (k, v) in &self.queries {
query_string = match query_string.as_str() {
"" => format!("?{}={}", k, v),
_ => format!("{}&{}={}", &query_string, k, v)
};
}
format!("{}/{}", self.base_url, query_string)
}
// This is the part where the magic happens
// We changing the inner values (queries) and returning a
// mutable self object with lifetime 'a.
pub fn limit<'a>(&'a mut self, value: i32) -> &'a mut Self {
self.queries.insert(String::from("limit"), format!("{}", value));
self
}
pub fn search<'a>(&'a mut self, word: &str) -> &'a mut Self {
self.queries.insert(String::from("search"), String::from(word));
self
}
}
fn main() {
println!("{}",
UrlBuilder::new("https://example.com")
.limit(10)
.search("word")
.as_string()
)
The result is as excepted:
https://example.com/?limit=10&search=word