gpt4 book ai didi

if-statement - 如何将使用三元运算符的 C++ 代码移植到 Rust?

转载 作者:行者123 更新时间:2023-11-29 08:19:50 25 4
gpt4 key购买 nike

如何将此 C++ 代码移植到 Rust:

auto sgnR = (R >= 0.) ? 1. : -1.;

我看过一些使用 match 关键字的示例,但我不明白它是如何工作的。

最佳答案

Rust 没有三元运算符,因为它不是必需的。一切都评估为某个值,if/else 语句也不异常(exception):

let r = 42.42;
let sgn_r = if r >= 0. { 1. } else { -1. };

您会注意到,我还将您的变量名称更改为惯用的 Rust。标识符使用 snake_case

不要被 Rust 拥有的 ? 运算符搞糊涂了。这是 called the "try operator" and is used to propagate errors .


特别是对于这个代码,你可能应该使用f64::signum :

let r = 42.42_f64;
let sgn_r = r.signum();

关于if-statement - 如何将使用三元运算符的 C++ 代码移植到 Rust?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57978972/

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