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.
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.
var a int = 10 // Simple assignmentLet's explore the basic assignment operators:
=: Assigns the value on the right to the variable on the left.a = 20 // Assigns 20 to variable aGo 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.a += 10 // Equivalent to a = a + 10-=: Subtracts the right operand from the left operand and assigns the result.a -= 5 // Equivalent to a = a - 5*=: Multiplies the left operand by the right operand and assigns the result.a *= 2 // Equivalent to a = a * 2/=: Divides the left operand by the right operand and assigns the result.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.a %= 3 // Equivalent to a = a % 3Comparison 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.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")
}
}What does the `+=` operator do in Go?
Happy coding! 🤖💻💡