and_then Rust · 常用方法
当 Option/Result 是成功值时,用闭包继续加工;失败时保持失败不变。
怎么用
x.and_then(|v| ...);,用于链式处理成功值
小例子
let x = Some(2);
let y = x.and_then(|v| Some(v * 2));
println!("{:?}", y);
运行结果
Some(4)
提醒:Result 版本叫 and_then,失败时直接返回 Err
官方文档:https://doc.rust-lang.org/std/option/enum.Option.html#method.and_then
在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Rust全部词条