Chapter 27: Assignment

1. What Are Assignment Operators?

Assignment operators are used to assign a value to a variable (or modify an existing value).

In Go there are two kinds:

  • The normal assignment=
  • The compound assignment operators (+=, -=, *=, etc.)

Go has no:

  • ++x / –x as expressions (only as statements)
  • &&= / ||= logical compound assignments
  • **= power assignment
  • multiple assignment in one expression like Python a = b = 5

2. The Basic Assignment Operator: =

Go

Key rules:

  • You must use = when declaring with var or when re-assigning an already declared variable
  • Short declaration := can only be used inside functions and must introduce at least one new variable
Go

3. All Compound Assignment Operators in Go

These are shorthand for operation + assignment.

Operator Equivalent to Works on Example Result after
+= a = a + b numbers, strings s += “!” string append
-= a = a – b numbers score -= penalty
*= a = a * b numbers total *= quantity
/= a = a / b numbers points /= 2 integer or float division
%= a = a % b integers only remainder %= divisor
&= a = a & b integers flags &= mask bitwise AND
= a = a b integers
^= a = a ^ b integers bits ^= toggle bitwise XOR
<<= a = a << b integers value <<= 3 left shift
>>= a = a >> b integers large >>= 1 right shift
&^= a = a &^ b integers flags &^= ForbiddenBit bit clear (Go-specific)

No compound assignment for logical operators (&&=, ||=) — intentional design choice.

4. Real Runnable Examples

Create assignment_operators.go and try these:

Go

5. Common Beginner Mistakes & How to Avoid Them

  1. Forgetting to assign back when using compound operators
Go
  1. Trying to use += on untyped constants or wrong types
Go
  1. Expecting ++ / — to be usable in expressions
Go
  1. Using = instead of := when you want short declaration
Go

6. Quick Practice Questions for You

Try to write one-liners that do the following (predict result first):

  1. Start with points := 150, subtract 25, then multiply by 2
  2. Start with status := 0b1010, set the 3rd bit (0-based) using |=
  3. Start with text := “Go is”, append ” awesome!” using +=
  4. Swap two variables a=5, b=10 using multiple assignment

Which operator did you use most?

Any part still confusing?

  • Why no **= power assignment?
  • Why no logical compound assignment?
  • Difference between a += b and a = a + b in performance?
  • Or ready for comparison operators next?

Keep typing small pieces and printing results — assignment operators are used in literally every non-trivial function you’ll write.

You’re progressing beautifully — keep asking! 💪🇮🇳🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *