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++;
}
and received the following error:
error: expected expression, found `+`
--> src\main.rs:3:12
|
3 | my_var++;
| ^
What's wrong with my code?
Increment (++) and decrement (--) operators are not supported in Rust. From Rust's FAQ: Why doesn't Rust have increment and decrement operators? Preincrement and postincrement (and the decrement equivalents), while convenient, are also fairly complex.
In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent.
1) Increment Operators: The increment operator is used to increment the value of a variable in an expression. In the Pre-Increment, the value is first incremented and then used inside the expression. Whereas in the Post-Increment, the value is first used inside the expression and then incremented.
A program can increment by 1 the value of a variable called c using the increment operator, ++, rather than the expression c=c+1 or c+=1.
Increment (++) and decrement (--) operators are not supported in Rust.
From Rust's FAQ:
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
orx += 1
is only slightly longer, but unambiguous.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With