我有一个类型为 Option 的参数,我需要在 http get 请求中使用它,但是 Option 类型将 Some(T) 放入格式化的 url

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

此函数用于发出 http get 请求并使用 select 或 select css 的特定 class。

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
}

输出:

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

基本上我的问题是有什么方法可以删除 Some( ) 并只保留该值。 这是 http get 请求的样子 btw:

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

已修复:let url = url_final.replace("\"", "");

还添加了:

amount.unwrap_or_default from.unwrap_or_default to.unwrap_or_default

Option<T>Debug 实现将打印 SomeNone 变体名称。这就是 Debug 的意义所在,这就是您在格式字符串中使用 {:?} 时所得到的结果。

您可以使用 unwrap_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()
);

鉴于您正在使用 reqwest,一个更好的方法是为您的查询参数使用一个结构,并使用 serde 来省略 None 值:

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?;