This is a tiny helper crate for simplifying the construction of URL query strings.
The initial ? question mark is automatically prepended.
QueryString borrows its keys and values and allocates no strings at all —
neither while building nor while rendering. Only the pair list itself is a
single Vec allocation:
use query_string_builder::QueryString;
fn main() {
let tasty = true;
let weight = 70.0;
let qs = QueryString::new()
.with("q", "apple")
.with("tasty", &tasty)
.with("weight", &weight)
.with_opt("color", None::<&str>)
.with_opt("category", Some("fruits and vegetables?"));
assert_eq!(
format!("https://example.com/{qs}"),
"https://example.com/?q=apple&tasty=true&weight=70&category=fruits%20and%20vegetables?"
);
}If you want to store the query string in a struct or return it from a function
without dealing with lifetimes, use QueryStringOwned — the same API, but it
eagerly converts keys and values to owned Strings:
use query_string_builder::QueryStringOwned;
fn build_query() -> QueryStringOwned {
QueryStringOwned::new()
.with("q", "apple")
.with("answer", 42)
}A borrowing builder can also be converted with qs.into_owned().
Because QueryString borrows its values, inline temporaries don't live long
enough — bind them to a variable first:
// Does not compile: the String temporary is dropped at the end of the statement.
let qs = QueryString::new().with("answer", &42.to_string());
println!("{qs}");// Bind first instead:
let answer = 42.to_string();
let qs = QueryString::new().with("answer", &answer);