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

如何在迭代器链中将Result转为Option?能否简化现有代码?

简化你的Rust代码示例

这段代码完全可以简化,不用手动写match分支。String::from_utf8返回的Result类型自带ok()方法,它会把Ok(value)转为Some(value),Err(_)转为None,刚好契合filter_map的要求。

简化后的代码如下:

/* Turn a Vec<Vec<u8>> into a Vec<String>, without re-allocating the inner bytes. */
let lines: Vec<String> = u8_lines
    .into_iter()
    .filter_map(|u8_line| String::from_utf8(u8_line).ok())
    .collect();

你也可以进一步用方法引用拆分步骤来简化:

let lines: Vec<String> = u8_lines
    .into_iter()
    .filter_map(String::from_utf8)
    .filter_map(Result::ok)
    .collect();

不过第一种写法已经足够简洁易读,是日常开发里更常用的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:40:21