[Solved! With two amazing answers!] How to increment in Rust?

In my code there is this line..
let mut ss = 0;
How would I increment it in a new function? Would I have to write it like this?

fn increment <n:int>{
    *n = *n+1;
}
fn main{
    ...
    let mut ss = 0;
    ...
    increment(ss);
}

This is my first time writing in Rust so I'm kind of lost with the syntax. Thanks for all the help and guidance!

The standard way to increment is with +=, so ss += 1;.

Rust doesn't provide a ++ operator for two primary reasons:

  • The primary motivator for ++ is for C-style for(init;condition;increment) loops, which aren't present at all in Rust. Instead, you use for pattern in iterator, so there's no need to manually increment your iterator cursor.
  • The ordering rules around ++ as an expression are nonobvious, even for experienced developers. On the other hand, += is a statement[1] with always clear ordering, and barely longer than ++ as a statement.

Language lawyer minutia and pedantry below.

[1]: Well, in actuality, += isn't a statement. place += value is an expression returning () ("unit", the type with only one value, the empty tuple). As far as I'm aware, there's only one actual statement in Rust: let[2]. Even assignment is just a ()-returning expression.

[2]: And there's experimental work that makes even that not true, allowing the use of let as an expression (in some restricted contexts).

1 Like

Here's a quick example:

// The `&mut` means I'm passing something that can be modified by reference
// I.e. I can modify the original in place
//
// There are many types of integers: isize, usize, i32, u64, etc.
// I've chosen `isize` arbitrarily
fn increment(n: &mut isize) {
    *n += 1;
}

fn main() {
    let mut ss = 0;
    increment(&mut ss);
    println!("{}", ss);
}

I recommend reading the book to help get you started.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.