Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile error when trying to use increment operator

Tags:

rust

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?

like image 637
Alex Lipov Avatar asked Oct 16 '16 18:10

Alex Lipov


People also ask

Can you do += in Rust?

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.

Can we use ++ i ++ in C?

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.

How do you use increment operator?

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.

How do you add increments in C++?

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.


1 Answers

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 or x += 1 is only slightly longer, but unambiguous.

like image 61
Alex Lipov Avatar answered Sep 30 '22 02:09

Alex Lipov