如何将使用三元运算符的 C++ 代码移植到 Rust? [英] How can I port C++ code that uses the ternary operator to Rust?
问题描述
如何将此 C++ 代码移植到 Rust:
How can I port this C++ code to Rust:
auto sgnR = (R >= 0.) ? 1. : -1.;
我看过一些带有 match
关键字的例子,但我不明白它是如何工作的.
I have seen some examples with the match
keyword, but I don't understand how it works.
推荐答案
Rust 没有三元运算符,因为它不需要.一切都会评估为某个值,if
/else
语句也不例外:
Rust does not have the ternary operator because it's not needed. Everything evaluates to some value, and if
/ else
statements are no exception:
let r = 42.42;
let sgn_r = if r >= 0. { 1. } else { -1. };
您会注意到,我还将您的变量名称更改为惯用的 Rust.标识符使用snake_case
.
You'll note that I've also changed your variable names to be idiomatic Rust. Identifiers use snake_case
.
不要被 Rust 确实 拥有的 ?
操作符弄糊涂了.这是 称为尝试操作符",用于传播错误.
Do not be confused by the ?
operator that Rust does have. This is called the "try operator" and is used to propagate errors.
特别是对于这个代码,您可能应该使用f64::signum
:
Specifically for this code, it's likely you should use f64::signum
:
let r = 42.42_f64;
let sgn_r = r.signum();
这篇关于如何将使用三元运算符的 C++ 代码移植到 Rust?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!