Lesson Overview

Fasten your seatbelts, coder! Today, we're immersing ourselves in Go, mastering arithmetic and logical operations on primitive types. These abilities are vital for data manipulation and decision-making during our coding adventure.

Arithmetic Operations Exposed

Remember that Go's primitive data types include int for whole numbers, float64 for decimal numbers, bool for true/false values, and string for textual content. Both int and float64 exhibit constraints in their numerical spans, which we'll explore when we discuss overflow later in this lesson.

We can perform arithmetic operations — addition (+), subtraction (-), multiplication (*), division (/), and modulus — the remainder of the division (%) — on numerical types. Here's how we do it:

package main
import "fmt"

func main() {
    var a int = 10
    var b int = 2
    fmt.Println(a + b) // Outputs: 12
    fmt.Println(a - b) // Outputs: 8
    fmt.Println(a * b) // Outputs: 20
    fmt.Println(a / b) // Outputs: 5
    fmt.Println(a % b) // Outputs: 0
}

Go supports alteration of order using parentheses and provides the modulus (%) operation, handy for determining whether numbers are even or odd!

Logical Operations Demystified

Logical operators — && (AND), || (OR), ! (NOT) — function as decision-makers in Go, returning bool values — true or false. Here's how we can utilise them with two bool variables:

package main
import "fmt"

func main() {
    fmt.Println(true && true) // true
    fmt.Println(true && false) // false
    fmt.Println(false && true) // false
    fmt.Println(false && false) // false

    fmt.Println(true || true) // true
    fmt.Println(true || false) // true
    fmt.Println(false || true) // true
    fmt.Println(false || false) // false

    fmt.Println(!true) // false
    fmt.Println(!false) // true
}

In this case, && yields true only if both boolean inputs are true, || outputs true if either of the inputs is true, and ! reverses the boolean value.

However, the primary use of logical operations is with variables. Let's quickly illustrate the basic usage:

package main
import "fmt"

func main() {
    var speed int = 60
    var minSpeed int = 30
    var maxSpeed int = 70
    // Check if the speed is within the accepted range.
    fmt.Println(speed > minSpeed && speed < maxSpeed); // Prints: true
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal