尝试使用增量运算符时编译错误 [英] Compile error when trying to use increment operator

查看:93
本文介绍了尝试使用增量运算符时编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个副项目工作期间,我尝试使用增量运算符,如下所示:

During work on a side project I've tried to use an increment operator, as following:

fn main() {
    let mut my_var = 5;
    my_var++;
}

并收到以下错误:

error: expected expression, found `+`
 --> src\main.rs:3:12
  |
3 |     my_var++;
  |            ^

我的代码有什么问题?

推荐答案

自增 (++) 和自减 (--) 运算符在 Rust 中不支持.

Increment (++) and decrement (--) operators are not supported in Rust.

来自 Rust 常见问题解答:

为什么 Rust 没有自增和自减运算符?
前增量和后增量(以及减量等价物),而方便,也比较复杂.他们需要了解评估顺序,通常会导致细微的错误和未定义的行为在 C 和 C++ 中.x = x + 1x += 1 只是稍微长一点,但是明确无误.

Why doesn't Rust have increment and decrement operators?
Preincrement and postincrement (and the decrement equivalents), while convenient, are also fairly complex. They require knowledge of evaluation order, and often lead to subtle bugs and undefined behavior in C and C++. x = x + 1 or x += 1 is only slightly longer, but unambiguous.

这篇关于尝试使用增量运算符时编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆