gpt4 book ai didi

rust - 模式匹配如何与 Rust 中的 ref 一起工作?

转载 作者:行者123 更新时间:2023-12-03 11:41:50 25 4
gpt4 key购买 nike

刚刚从 here 中发现了这个代码:

...
let mut txn = client.transaction()?;
loop {
let mut sp = txn.savepoint("cockroach_restart")?;
match op(&mut sp).and_then(|t| sp.commit().map(|_| t)) {
Err(ref err)
if err
.code()
.map(|e| *e == SqlState::T_R_SERIALIZATION_FAILURE)
.unwrap_or(false) => {}
r => break r,
}
}
.and_then(|t| txn.commit().map(|_| t))
...
不太清楚 match 内部发生了什么堵塞。
  • 为什么不处理 Ok处理后的变体 Err ?
  • 在哪里r来自?
  • err.code()...的逻辑是什么? ?它是从指针到 bool 的映射,然后在 bool 上展开????然后什么都不做?
  • 最佳答案

    Why is there no handling for Ok variant after handling Err?


    匹配的第二个分支是匹配任何值的全能模式,因此它覆盖了 Ok变体,以及 Err第一个变体中的守卫失败的变体。

    Where does r come from?


    当标识符如 r用作模式,它表示捕获匹配值的新局部变量。

    What's the logic with err.code()...?

    postgres::Error::code()返回 Option<&SqlState> .如果提供了代码(选项是 Some ),并且等于 SqlState::T_R_SERIALIZATION_FAILURE ,循环继续。如果不是 T_R_SERIALIZATION_FAILURE或未提供(选项为 None ),匹配保护返回 false 并改为执行捕获所有模式,停止循环。
    解开 code() 的处理一步步:
  • postgres::Error::code()返回 Option<&SqlState> .
  • Option<&SqlState>::map(closure) map Option<&SqlState>Option<type returned by the closure> . The closure is called only if the option is Some , 否则 Option::map刚刚返回 None .由于我们的闭包只是评估 == ,它返回 boolmap因此返回 Option<bool> . (闭包必须使用 * 来取消引用该值,因为它接收 &SqlState 。)
  • Option<bool>::unwrap_or(default_value)如果选项为 Some,则计算为选项中的值并到 default_value如果是 None ,有效转换 Option<bool>bool ,我们需要为 if .
  • 关于rust - 模式匹配如何与 Rust 中的 ref 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62733968/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com