Go Assignment Operators 🎯

beginner
21 min

Go Assignment Operators 🎯

Welcome to our comprehensive guide on Go Assignment Operators! This lesson is designed to be your friendly companion as you learn about these essential tools in the Go programming language.

Understanding Assignment Operators 📝

Assignment operators in Go are used to assign values to variables. They make our life easier by providing shortcut notations for a sequence of operations.

go
var a int = 10 // Simple assignment

Basic Assignment Operators 💡

Let's explore the basic assignment operators:

  • =: Assigns the value on the right to the variable on the left.
go
a = 20 // Assigns 20 to variable a

Shorthand Assignment Operators 💡

Go also offers shorthand assignment operators, which perform an operation and assign the result back to the same variable.

  • +=: Adds the right operand to the left operand and assigns the result.
go
a += 10 // Equivalent to a = a + 10
  • -=: Subtracts the right operand from the left operand and assigns the result.
go
a -= 5 // Equivalent to a = a - 5
  • *=: Multiplies the left operand by the right operand and assigns the result.
go
a *= 2 // Equivalent to a = a * 2
  • /=: Divides the left operand by the right operand and assigns the result.
go
a /= 4 // Equivalent to a = a / 4
  • %=: Calculates the remainder of the division of the left operand by the right operand and assigns the result.
go
a %= 3 // Equivalent to a = a % 3

Comparison Operators 📝

Comparison operators are used to compare two operands and return a boolean value (true or false). They are not assignment operators, but they are essential for conditional statements.

  • ==: Checks if the operands are equal.
  • !=: Checks if the operands are not equal.
  • <: Checks if the left operand is less than the right operand.
  • >: Checks if the left operand is greater than the right operand.
  • <=: Checks if the left operand is less than or equal to the right operand.
  • >=: Checks if the left operand is greater than or equal to the right operand.

Practical Example 💡

go
package main import "fmt" func main() { a := 10 b := 20 if a < b { fmt.Println("a is less than b") } else if a > b { fmt.Println("a is greater than b") } else { fmt.Println("a is equal to b") } a += 5 b -= 5 if a > b { fmt.Println("a is greater than b after assignment") } else { fmt.Println("a is less than or equal to b after assignment") } }

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `+=` operator do in Go?

Happy coding! 🤖💻💡