如何在关闭之外传播错误?
我在返回 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`
如何在关闭之外传播错误?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法通过
sort_by
的返回值表示错误,也不能在进行过程中流产。但是,您可以通过在闭合外访问可变变量并返回虚拟值来偷走错误:playground> Playground
尽管我怀疑您会
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:Playground
Though I suspect that you'd be better served by
ordered_float
(orf64::total_cmp
(stable since 1.62)) to make sure you can always sort (I haven't tried it yet, but it looks nice.)