如何将使用三元运算符的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.;
我见过一些匹配的例子
关键字,但我不了解它的工作原理。
I have seen some examples with the match
keyword, but I don't understand how it works.
推荐答案
Rust没有三元运算符,因为它不是必需的。一切都会达到一定的价值,并且 c 或
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.
专门针对 this 代码,您可能应该使用 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屋!