In Go, assignment operators are essential for assigning values to variables and performing operations efficiently. Below is an overview of these operators, their usage, and examples.
Basic Assignment Operator
The assignment operator (=
) assigns a specific value to a variable. For example:
Go
x
package main
import "fmt"
func main() {
var ducati = 10
fmt.Println(ducati)
}
In this example, the value 10
is assigned to the variable ducati
using the =
operator.
Compound Assignment Operators
Compound assignment operators perform operations and assign the results back to variables. For instance, the addition assignment operator (+=
) increases the value of a variable by a certain amount:
Go
package main
import "fmt"
func main() {
var yamaha = 10
yamaha += 5
fmt.Println(yamaha)
}
Here, yamaha += 5
is equivalent to yamaha = yamaha + 5
.
Complete List of Assignment Operators
Below is a table summarizing all assignment operators in Go:
Operator | Example | Equivalent To |
---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
&= | x &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= | x ^= 3 | x = x ^ 3 |
>>= | x >>= 3 | x = x >> 3 |
<<= | x <<= 3 | x = x << 3 |