You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust函数遇错返回空String问题:unwrap_or_else类型不匹配求解

解决Rust获取HTML函数的错误处理问题

你的问题核心是类型不匹配:reqwest::blocking::get返回的是Result<Response, Error>类型,但你在第一个unwrap_or_else里返回了String,和变量response的类型冲突。要实现“任何错误都返回空字符串”的需求,可以通过链式处理Result的方式简化代码:

fn get_html(address: &str) -> String {
    reqwest::blocking::get(address)
        .and_then(|response| response.text())
        .unwrap_or_else(|_| String::new())
}

代码说明:

  • reqwest::blocking::get(address):发起请求,返回Result<Response, Error>类型结果。
  • .and_then(|response| response.text()):请求成功时,调用response.text()将响应体转为字符串,返回Result<String, Error>;请求失败时直接传递错误到下一步。
  • .unwrap_or_else(|_| String::new()):整个调用链中任意一步出错,就返回空字符串;全部成功则返回获取到的HTML内容。

也可以用map结合unwrap_or_default实现,效果完全一致:

fn get_html(address: &str) -> String {
    reqwest::blocking::get(address)
        .map(|response| response.text().unwrap_or_default())
        .unwrap_or_default()
}

unwrap_or_default()对于String类型来说,默认返回值就是空字符串,和String::new()等价。

内容的提问来源于stack exchange,提问作者Marcel Kopera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 10:35:16