Use compound assignments and increment statements
Use compound assignments and increment statements
Compound assignment combines an operation with storing its result. For a variable x, x += 2 adds two and stores the result. Go supports +=, -=, *=, /=, %=, and corresponding bitwise and shift assignments. The left operand is evaluated only once.
package main
import "fmt"
func main() { balance := 100 balance += 30 balance -= 20 fmt.Println(balance) balance *= 2 fmt.Println(balance)}The balance becomes 110 after the deposit and withdrawal, then doubles to 220. The variable must be assignable and the operation must be valid for its type.
Increment and decrement are statements
package main
import "fmt"
func main() { count := 4 count++ fmt.Println(count) count-- fmt.Println(count)}count++ and count-- change a variable by one. They do not yield a value, so next := count++ is invalid. Go has no prefix increment ++count. Use separate statements; do not copy increment expressions from C or JavaScript.
Try it locally
Start with 12 tickets, add 5, subtract 3, then increment once. Print the result. Expected: 15.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Expressions and Arithmetic 05: Use compound assignments and increment statements
Check the lesson objective before moving on.
What does x += 3 do?
Which is valid as a standalone statement?