When we hear the term “operators,” many of us immediately think of mathematical operations like addition, subtraction, division, or exponentiation. However, operators go far beyond mathematics. They are powerful tools used to compare, manipulate, and evaluate data in various contexts.
For instance, in programming and data analysis, operators can be used to check conditions, such as determining whether a price in a trading application is too low or too high. Additionally, operators enable us to perform actions like combining or transforming data.
Imagine adding up the costs of all items in a shopping cart to calculate the total price — that’s another example of operators in action. Their versatility makes them essential in both logical and numerical problem-solving.
Types of Operators
• Arithmetic operators: Used for math-related tasks such as addition, subtraction, and multiplication
• Comparison operators: Used to compare two values; for example, to check if they are equal, not equal, less than, or greater than each other
• Logical operators: Used with Boolean values to determine whether both are true, only one is true, or whether a Boolean value is false
• Address operators: Related to pointers; we will explore this in a separate article
• Receive operators: Used when working with Go channels; we will cover this later when discussing channels
Arithmetic Operators
To demonstrate arithmetic operators, we will simulate a shopping bill. To build our simulation, we will use both arithmetic and comparison operators. Let’s start by exploring the primary uses of operators.
This demonstrates the use of arithmetic operators like +, *, /, and - to calculate the shopping bill.
package mainimport "fmt"func main() { // List of item prices var item1, item2, item3 float64 = 19.99, 45.50, 12.75 // Applying arithmetic operations total := item1 + item2 + item3 // Sum of all items discount := 10.0 // Flat discount in percentage discountAmount := (total * discount) / 100 finalTotal := total - discountAmount // Displaying the bill fmt.Println("Item Prices:") fmt.Printf("Item 1: $%.2f\n", item1) fmt.Printf("Item 2: $%.2f\n", item2) fmt.Printf("Item 3: $%.2f\n", item3) fmt.Printf("Subtotal: $%.2f\n", total) fmt.Printf("Discount (%.2f%%): -$%.2f\n", discount, discountAmount) fmt.Printf("Total after Discount: $%.2f\n", finalTotal)}
• Adding item prices: The prices of individual items (item1, item2, item3) are added using the + operator to calculate the subtotal
• Calculating discount: The discount percentage is applied using the multiplication (*) and division (/) operators
• Subtracting discount: The discount amount is subtracted from the subtotal to get the final total
When you add a value to your current value, for example, it can become repetitive without shorthand operators.
What shorthand operators do we have?
--: Reduce a number by 1++: Increase a number by 1+=: Add and assign-=: Subtract and assign
We’ll use some examples of shorthand operators to demonstrate how they can make your code more compact and easier to write. We’ll create some variables and then use shorthand to modify them, printing the results as we go.
package mainimport "fmt"func main() { // Initial variables a := 10 b := 20 c := 5 // Print initial values fmt.Println("Initial values:") fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c) // Using shorthand operators // Add and assign a += 5 // equivalent to a = a + 5 fmt.Printf("After 'a += 5': a = %d\n", a) // Subtract and assign b -= 10 // equivalent to b = b - 10 fmt.Printf("After 'b -= 10': b = %d\n", b) // Multiply and assign c *= 2 // equivalent to c = c * 2 fmt.Printf("After 'c *= 2': c = %d\n", c) // Divide and assign c /= 3 // equivalent to c = c / 3 fmt.Printf("After 'c /= 3': c = %d\n", c) // Modulus and assign a %= 4 // equivalent to a = a % 4 fmt.Printf("After 'a %%= 4': a = %d\n", a) // Print final values fmt.Println("Final values:") fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c)}
Output:
a = 10, b = 20, c = 5After 'a += 5': a = 15After 'b -= 10': b = 10After 'c *= 2': c = 10After 'c /= 3': c = 3After 'a %= 4': a = 3Final values:a = 3, b = 10, c = 3
Comparing values
Logic in applications involves having your code make decisions. These decisions are based on comparing the values of variables to the rules you define, which take the form of comparisons.
We use a specific set of operators to perform these comparisons, and the result is always a Boolean value — either true or false. Often, you’ll need to make multiple comparisons to arrive at a single decision. To assist with this, logical operators come into play.
Logical operators primarily work with two values and always produce a Boolean result. They can only be used with Boolean values.
Comparison operators:
• ==: True if two values are the same
• !=: True if two values are not the same
• <: True if the left value is less than the right value
• <=: True if the left value is less or equal to the right value
• >: True if the left value is greater than the right value
• >=: True if the left value is greater than or equal to the right value
Logical operators:
• &&: True if the left and right values are both true
• ||: True if one or both the left and right values are true
• !: This operator only works with a single value and results in true if the value is false
Let’s look at an example of using some of these operators. Imagine you have two portfolios — stocks and crypto — and you want to compare the total value of each to determine where you have more allocated money.
package mainimport "fmt"func main() { // Portfolio values stocks := 15000.0 crypto := 10000.0 // Compare portfolio values fmt.Println("Portfolio Comparison:") // Using comparison operators if stocks == crypto { fmt.Println("Stocks and Crypto portfolios are equal in value.") } else if stocks > crypto { fmt.Println("Stocks portfolio is larger than Crypto portfolio.") } else { fmt.Println("Crypto portfolio is larger than Stocks portfolio.") } // Using logical operators riskyCrypto := crypto > 5000.0 && crypto < 20000.0 fmt.Printf("Is Crypto portfolio considered risky? %v", riskyCrypto) highStocksOrCrypto := stocks > 20000.0 || crypto > 20000.0 fmt.Printf("Do we have a high-value portfolio in either Stocks or Crypto? %v", highStocksOrCrypto) // Using NOT operator lowRiskStocks := !(stocks > 20000.0) fmt.Printf("Are Stocks portfolio considered low risk? %v", lowRiskStocks)}
Output:
Portfolio Comparison:Stocks portfolio is larger than Crypto portfolio.Is Crypto portfolio considered risky? trueDo we have a high-value portfolio in either Stocks or Crypto? falseAre Stocks portfolio considered low risk? true
Zero values
The zero value of a variable is its default value based on the type. In Go, each core type has a predefined zero value.
Bonus — Formatting Verbs in fmt.Printf
In the shorthand operators section, we use %d. There are more of these formatting options, which might seem unusual at first.
Let’s discuss what they are so that they no longer seem confusing.
The fmt.Printf function in Go uses a template language with “verbs” for formatting. These verbs allow you to control how a value is formatted and displayed when printed. For example, the %#v verb prints values in a Go-syntax-like representation, making it particularly helpful for debugging.