'I have an arg with type Option which i need to use in a http get request but Option type puts Some(T) into the formatted url [closed]

This is the function for making the http get request and using selector to select a specific class of css.

pub async fn test(amount: Option<&str>, from: Option<&str>, to: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
    let url_final = format!("https://www.xe.com/currencyconverter/convert/?Amount={:?}&From={:?}&To={:?}", amount, from, to); //used debug cuz Option does not impl Display
}

output:

https://www.xe.com/currencyconverter/convert/?Amount=Some(1)&From=Some("USD")&To=Some("HUF")

basically my question is there any way to remove the Some( ) and only leave the value. This is what the http get request looks like btw:

let req = reqwest::get(url_final).await?;

FIXED with: let url = url_final.replace("\"", "");

Also added:

amount.unwrap_or_default from.unwrap_or_default to.unwrap_or_default


Solution 1:[1]

The Debug implementation for Option<T> will print the Some and None variant names. That's the point of Debug, which is what you'll get when you use {:?} in a format string.

You can use unwrap_or("") or unwrap_or_default():

let url_final = format!(
    "https://www.xe.com/currencyconverter/convert/?Amount={}&From={}&To={}",
    amount.unwrap_or_default(),
    from.unwrap_or_default(),
    to.unwrap_or_default()
);

Given you are using reqwest, a nicer way to do this is to use a struct for your query parameters, and make use of serde to omit the None values:

use serde::Serialize;

#[derive(Serialize)]
#[serde(rename_all = "PascalCase")]
struct XeArgs<'a> {
    amount: Option<&'a str>,
    to: Option<&'a str>,
    from: Option<&'a str>,
}

let client = reqwest::Client::new();

let query = XeArgs {
    amount: None,
    to: Some("USD"),
    from: None,
};

let response = client
    .get("https://www.xe.com/currencyconverter/convert/")
    .query(&query)
    .send()
    .await?;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1