Introduction
Assignment operators help you store or update values in variables easily.
let mut variable = value; variable = new_value; // simple assignment variable += value; // add and assign variable -= value; // subtract and assign variable *= value; // multiply and assign variable /= value; // divide and assign variable %= value; // remainder and assign
mut to allow changing their value.let mut x = 5; x = 10;
let mut x = 5; x += 3; // x is now 8
let mut x = 10; x *= 2; // x is now 20
let mut x = 10; x %= 3; // x is now 1
fn main() {
let mut score = 10;
println!("Initial score: {}", score);
score += 5;
println!("After adding 5: {}", score);
score *= 2;
println!("After doubling: {}", score);
score -= 4;
println!("After subtracting 4: {}", score);
score /= 3;
println!("After dividing by 3: {}", score);
score %= 3;
println!("After remainder by 3: {}", score);
}mut if you want to change their values.+=, -=, *=, /=, and %= to combine math and assignment.mut) to use assignment operators.+= do?+= operator+= operator adds the right-hand side value to the left-hand side variable.+= means add and assign [OK]*= operator in Rust?mut. So let mut x = 5; is correct.*= is used as x *= 2; to multiply and assign.mut in wrong position*= x 2let mut a = 10;
a += 5;
a *= 2;
println!("{}", a);a += 5;a = 10, adding 5 gives a = 15.a *= 2;a = 30.let x = 8;
x -= 3;
println!("{}", x);x is declared without mut, so it is immutable.-= tries to subtract and assign a new value to x, which is not allowed for immutable variables.result?let mut result = 50; let change = 7; result %= change; result += 3; result *= 4;
result %= change;result = 1.result += 3;result = 4.result *= 4;result = 16.Pass the test and this pattern moves unknown