如何在关闭之外传播错误?

发布于 2025-02-10 09:43:33 字数 466 浏览 3 评论 0 原文

我在返回 result 的函数中有一个小片段:

list.sort_by(|a, b| a.re.partial_cmp(&b.re).unwrap()
                        .then(a.im.partial_cmp(&b.im).unwrap()));

但是我不喜欢Unrap。我宁愿用 .unwrap()替换,但这给了我错误:

cannot use the `?` operator in a closure that returns `std::cmp::Ordering`

如何在关闭之外传播错误?

I've got this little fragment in a function which returns Result:

list.sort_by(|a, b| a.re.partial_cmp(&b.re).unwrap()
                        .then(a.im.partial_cmp(&b.im).unwrap()));

but I don't like the unwrap. I'd rather replace the .unwrap() with ? but that gives me the error:

cannot use the `?` operator in a closure that returns `std::cmp::Ordering`

How can I propagate the error outside the closure?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ˇ宁静的妩媚 2025-02-17 09:43:33

您无法通过 sort_by 的返回值表示错误,也不能在进行过程中流产。但是,您可以通过在闭合外访问可变变量并返回虚拟值来偷走错误:

let mut failed = false;
list.sort_by(
    |a, b| match (a.re.partial_cmp(&b.re), a.im.partial_cmp(&b.im)) {
        (Some(reo), Some(imo)) => reo.then(imo),
        _ => {
            failed = true;
            Ordering::Equal
        }
    },
);
match failed {
    false => Ok(list),
    true => Err("I think not"),
}

playground> Playground

尽管我怀疑您会

  • 在列表中首先寻求NAN,并且您可以保持任何选择(您可以保持任何东西)然后取消包裹,因为它们真的永远不会发生),或
  • 使用 strouded_float (或 f64 :: total_cmp (稳定自1.62起)​​)以确保您始终可以分类(我还没有尝试过,但看起来不错。)

You can't indicate an error via the return value of sort_by, and you can't abort the sort while it's under way. But you can smuggle the error out by accessing a mutable variable outside of the closure and returning a dummy value:

let mut failed = false;
list.sort_by(
    |a, b| match (a.re.partial_cmp(&b.re), a.im.partial_cmp(&b.im)) {
        (Some(reo), Some(imo)) => reo.then(imo),
        _ => {
            failed = true;
            Ordering::Equal
        }
    },
);
match failed {
    false => Ok(list),
    true => Err("I think not"),
}

Playground

Though I suspect that you'd be better served by

  • first looking for NaNs in the list and not sorting at all if there are any (You can keep the unwraps then, as they'll really never occur), or
  • use something like ordered_float (or f64::total_cmp (stable since 1.62)) to make sure you can always sort (I haven't tried it yet, but it looks nice.)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文