Operators in Go are special symbols that perform operations on operands. They are essential for manipulating data and controlling program flow. Go supports various types of operators, each serving a specific purpose in your code.
Arithmetic operators perform mathematical calculations on numeric operands.
+
(Addition)-
(Subtraction)*
(Multiplication)/
(Division)%
(Modulus)These operators compare two values and return a boolean result.
==
(Equal to)!=
(Not equal to)<
(Less than)>
(Greater than)<=
(Less than or equal to)>=
(Greater than or equal to)Logical operators are used to combine conditional statements.
&&
(Logical AND)||
(Logical OR)!
(Logical NOT)These operators assign values to variables.
=
(Simple assignment)+=
, -=
, *=
, /=
, %=
(Compound assignment)Bitwise operators perform operations on individual bits of integer types.
&
(Bitwise AND)|
(Bitwise OR)^
(Bitwise XOR)<<
(Left shift)>>
(Right shift)
package main
import "fmt"
func main() {
a := 10
b := 3
sum := a + b
difference := a - b
product := a * b
quotient := a / b
remainder := a % b
fmt.Printf("Sum: %d\n", sum)
fmt.Printf("Difference: %d\n", difference)
fmt.Printf("Product: %d\n", product)
fmt.Printf("Quotient: %d\n", quotient)
fmt.Printf("Remainder: %d\n", remainder)
// Compound assignment
a += 5
fmt.Printf("a after += 5: %d\n", a)
}
package main
import "fmt"
func main() {
x := 5
y := 10
fmt.Printf("x == y: %t\n", x == y)
fmt.Printf("x != y: %t\n", x != y)
fmt.Printf("x < y: %t\n", x < y)
fmt.Printf("x > y: %t\n", x > y)
condition1 := x < y
condition2 := x > 0
fmt.Printf("condition1 && condition2: %t\n", condition1 && condition2)
fmt.Printf("condition1 || condition2: %t\n", condition1 || condition2)
fmt.Printf("!condition1: %t\n", !condition1)
}
Understanding Go operators is crucial for effective programming. They form the foundation for manipulating data, controlling program flow, and implementing complex logic in your Go applications. As you progress in your Go journey, you'll find these operators indispensable in various scenarios, from simple calculations to complex algorithmic implementations.
To further enhance your Go skills, explore related concepts such as Go Variables, Go Data Types, and Go Constants. These topics will provide a comprehensive understanding of how to work with data in Go, complementing your knowledge of operators.