0
0
Goprogramming~5 mins

Assignment operators in Go

Choose your learning style9 modes available
Introduction
Assignment operators help you store or update values in variables easily.
When you want to save a value in a variable.
When you want to add or subtract a number from a variable's current value.
When you want to multiply or divide a variable by a number and save the result.
When you want to quickly update a variable without writing the variable name twice.
Syntax
Go
variable = value
variable += value
variable -= value
variable *= value
variable /= value
variable %= value
The '=' operator assigns a new value to a variable.
Operators like '+=', '-=', '*=', '/=', '%=' update the variable by applying the operation with the right value.
Examples
Adds 5 to x and saves the result back in x.
Go
x := 10
x += 5  // x is now 15
Subtracts 4 from y and saves the result back in y.
Go
y := 20
y -= 4  // y is now 16
Multiplies z by 7 and saves the result back in z.
Go
z := 3
z *= 7  // z is now 21
Divides a by 3 and saves the result back in a.
Go
a := 15
a /= 3  // a is now 5
Sample Program
This program shows how to use different assignment operators to update the value of the variable 'score'.
Go
package main
import "fmt"

func main() {
    var score int = 10
    fmt.Println("Initial score:", score)

    score += 5
    fmt.Println("After adding 5:", score)

    score -= 3
    fmt.Println("After subtracting 3:", score)

    score *= 2
    fmt.Println("After multiplying by 2:", score)

    score /= 4
    fmt.Println("After dividing by 4:", score)

    score %= 3
    fmt.Println("After modulo 3:", score)
}
OutputSuccess
Important Notes
Assignment operators make your code shorter and easier to read.
Be careful with division and modulo operators to avoid dividing by zero.
These operators work only with variables, not with constants or literals.
Summary
Assignment operators store or update values in variables.
They combine an operation and assignment in one step.
Common operators include '=', '+=', '-=', '*=', '/=', and '%='.