Data Processing with Operators

GolangGolangBeginner
Practice Now

Introduction

After data is saved in variables in programming language, how should we process it?

This is when we need operators to perform calculations on the data that has been saved. In this section, we will learn the following:

Knowledge Points:

  • Arithmetic operators
  • Relational operators
  • Logical operators
  • Assignment operators

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Golang`")) -.-> go/BasicsGroup(["`Basics`"]) go(("`Golang`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go(("`Golang`")) -.-> go/DataTypesandStructuresGroup(["`Data Types and Structures`"]) go(("`Golang`")) -.-> go/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) go/BasicsGroup -.-> go/variables("`Variables`") go/FunctionsandControlFlowGroup -.-> go/functions("`Functions`") go/FunctionsandControlFlowGroup -.-> go/closures("`Closures`") go/DataTypesandStructuresGroup -.-> go/pointers("`Pointers`") go/ObjectOrientedProgrammingGroup -.-> go/generics("`Generics`") subgraph Lab Skills go/variables -.-> lab-149066{{"`Data Processing with Operators`"}} go/functions -.-> lab-149066{{"`Data Processing with Operators`"}} go/closures -.-> lab-149066{{"`Data Processing with Operators`"}} go/pointers -.-> lab-149066{{"`Data Processing with Operators`"}} go/generics -.-> lab-149066{{"`Data Processing with Operators`"}} end

Basic Form

Arithmetic operators are the most basic operators, representing the most basic calculation methods.

Operator Function
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder)

Create a file named opePractice.go in the home/project/ directory:

cd ~/project
touch opePractice.go

Write the following code in it:

package main

import "fmt"

func main() {
    a := 10
    b := 3
    fmt.Println("a =", a, "b =", b)
    fmt.Println("-----")

    // Addition, subtraction, and multiplication
    fmt.Println("a + b =", a+b) // = 13
    fmt.Println("a - b =", a-b) // = 7
    fmt.Println("b - a =", b-a) // = -7
    fmt.Println("a * b =", b*a) // = 30

    // Division
    // In Go, if an integer is divided, it will be rounded down.
    fmt.Println("a / b =", b/a) // = 0
    // But if a floating-point number is divided, there will be no such problem.
    fmt.Println("10.0 / 3 =", 10.0/3) // = 3.3333

    // Modulus calculation: general form
    fmt.Println("10 % 3 =", a%b) // = 1
    // Modulus calculation with negative numbers
    // Calculation method: remainder = dividend - (dividend / divisor) * divisor
    fmt.Println("10%-3=", 10%-3)   // =1
    fmt.Println("-10%3=", -10%3)   // -1
    fmt.Println("-10%-3=", -10%-3) // =-1
}

Run the code, and pay special attention to how the negative remainder is calculated.

cd ~/project
go run opePractice.go
a = 10 b = 3
-----
a + b = 13
a - b = 7
b - a = -7
a * b = 30
a / b = 0
10.0 / 3 = 3.3333333333333335
10 % 3 = 1
10%-3= 1
-10%3= -1
-10%-3= -1

Increment and Decrement Operators

In Go, ++ (increment) and -- (decrement) are standalone statements and can only be used independently, they are not operators.

The following code is incorrect:

var a int = 5
var i int = 0
a = i++ // Incorrect usage, increment can only be used independently
a = i-- // Incorrect usage, decrement can only be used independently
a = ++i // Incorrect usage, Go does not have pre-increment
a = --i // Incorrect usage, Go does not have pre-decrement

The proper syntax is:

var i = 0
i++
i++
fmt.Println(i)

Write the following code in opePractice.go:

Complete the code. Change the value of variable i using the increment operator, so that the value of variable a becomes 16:

package main

import "fmt"

func main() {
    var a int = 15
    var i int = 0
    /* Write code here

     */
    a = a + i
    fmt.Println(a)
    // Complete the code to make the output of a equal 16
}
âœĻ Check Solution and Practice

Relational Operators

What are relational operators?

Relational operators are a form of comparison, describing the relationship between two values. They determine whether two values are equal, whether one is greater or less than the other.

Operator Relationship
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

The above operators return true if the condition is successful and false otherwise.

Write the following code in opePractice.go:

package main

import "fmt"

func main() {
    // Use of relational operators
    var a int = 7
    var b int = 6
    // Check if equal
    fmt.Println(a == b)  //false
    // Check if not equal
    fmt.Println(a != b)  //true
    // Check if a is greater than b
    fmt.Println(a > b)   //true
    // Check if a is greater than or equal to b
    fmt.Println(a >= b)  //true
    // Check if a is less than b
    fmt.Println(a < b)   //false
    // Check if a is less than or equal to b
    fmt.Println(a <= b)  //false
    // Check if 1 is equal to 1
    JudgeValue := 1 == 1 //true
    fmt.Println(JudgeValue)
}

Run the code:

cd ~/project
go run opePractice.go

In the above code, we performed relational comparisons based on the variables a and b.

Students can modify variable values to change the comparison results and gain a deeper understanding of relational operators.

Logical Operators

What are logical operators?

Logical operators are an advanced form of relational operators. They are primarily used to combine relational operators for further evaluation.

Operator Relationship Explanation
&& And If both sides are true, the result is true
|| Or If either side is true, the result is true
! Not If the condition is false, the result is true

Write the following code in opePractice.go:

package main

import (
    "fmt"
)

func main() {
    // Demonstrating logical AND operator &&
    var age int = 18
    if age > 15 && age < 30 {
        fmt.Println("Age is between 15 and 30")
    }
    if age > 30 && age < 80 {
        fmt.Println("Age is between 30 and 80")
    }
    // Demonstrating logical OR operator ||
    if age > 15 || age < 30 {
        fmt.Println("Age is greater than 15 or less than 30")
    }
    if age > 30 || age < 40 {
        fmt.Println("Age is greater than 30 or less than 40")
    }
    // Demonstrating logical NOT operator !
    if age > 30 {
        fmt.Println("Age is greater than 30")
    }
    if !(age > 30) {
        fmt.Println("Age is not greater than 30")
    }
}

In the code above, we performed a series of logical evaluations based on the variable age value of 18.

Students can modify the age variable value and run the code to observe the changes in output.

Execution Order of Logical Operators

When using logical AND and logical OR operators, Go needs to determine the boolean values on both sides of the operator. But which side is evaluated first?

Let's explore this together.

Write the following code in opePractice.go:

package main

import "fmt"

func leftFunc(flag bool) bool {
    fmt.Println("Left function is called!")
    return flag
}

func rightFunc(flag bool) bool {
    fmt.Println("Right function is called!")
    return true
}

func main() {
    if leftFunc(true) && rightFunc(true) {
        fmt.Println("Evaluation is complete")
    }
}

Run the code:

Left function is called!
Right function is called!
Evaluation is complete

It is not difficult to find out that in the logical AND operation, the left condition is evaluated first, and then the right condition is evaluated.

What about the logical OR operation? Write the following code in opePractice.go:

package main

import "fmt"

func leftFunc(flag bool) bool {
    fmt.Println("Left function is called!")
    return flag
}

func rightFunc(flag bool) bool {
    fmt.Println("Right function is called!")
    return true
}

func main() {
    if leftFunc(true) || rightFunc(true) {
        fmt.Println("Logical OR evaluation is complete")
    }
}

Run the code:

Left function is called!
Logical OR evaluation is complete

The evaluation order of both logical AND and logical OR operations is from left to right.

However, in the logical OR operation, if the left condition is true, the right condition is not evaluated.

Therefore, in actual development, we should place the conditions that are more likely to be evaluated to the left of the logical OR operator, reducing the execution time of the program.

Assignment Operators

In previous experiments, we have often used assignment operators. The core function of assignment operators is to assign the value of an expression to a left value.

Left Value: The expression or variable to the left of the assignment operator (=) that can be written into.

In actual development, we often need to add or subtract one variable from another.

Based on what we've learned, we could write code like this:

x = x + 1

But this kind of code is very common in actual development, so we provide a shorthand form for it:

x += 1

Similarly, commonly used assignment operators include:

Operator Description
= Basic assignment operator
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign (remainder)

Write the following code in opePractice.go:

package main

import "fmt"

func main() {
    x := 11
    fmt.Println("The initial value of x:", x)
    x += 5 // x = x + 5
    fmt.Println("Value after x += 5:", x)
    x -= 5 // x = x - 5
    fmt.Println("Value after x -= 5:", x)
    x *= 5 // x = x * 5
    fmt.Println("Value after x *= 5:", x)
    x /= 5
    fmt.Println("Value after x /= 5:", x)
    x %= 3
    fmt.Println("Value after x %= 3:", x)
}

In the code above, we assign an initial value of 11 to variable x and perform basic arithmetic (addition, subtraction, multiplication), division, and modulus calculations.

You can modify the variable's value to see how the assignment operators work.

Summary

Let's review what we learned in this lab:

  • The use of arithmetic operators
  • The use of relational operators
  • The use of logical operators
  • The use of assignment operators

In this lab, we have discussed how to use operators in Go. We have demonstrated various operators and their usage. In the next lab, we will introduce a challenge to deepen your understanding of variables and operators.

Other Golang Tutorials you may like