Lesson Introduction and Plan

Greetings! Today, we're venturing into the rewarding realm of Go comparison operators. These operators are of paramount importance as they control the flow of code by enabling value comparisons.

Our goal for this session is to deepen our understanding of the usage of comparison operators in Go programs. We will investigate various Go comparison operators and reinforce your learning through real-world examples.

Exploring Go Comparison Operators

Imagine operating a submarine in the deep sea. Here, you determine your routes by evaluating conditions such as the distances to underwater landmarks. These decisions boil down to comparisons, similar to situations encountered in programming. In Go, we use comparison operators to facilitate such rational decision-making.

The Go programming language includes six comparison operators: equal to (==), not equal to (!=), greater than (>), less than(<), greater than or equal to (>=), and less than or equal to (<=). These operators return either true or false, also known as Boolean values.

Consider this comparison of a submarine's speed in relation to an ocean current as an example:

var submarineSpeed = 30  // speed in knots
var currentSpeed = 20    // speed in knots 
fmt.Println("Is the submarine faster than the ocean current? ", submarineSpeed > currentSpeed)
// Prints: Is the submarine faster than the ocean current? true

In the above code, we used the > operator to compare the submarineSpeed and the currentSpeed. The result is true because the submarineSpeed is greater than the currentSpeed.

Exploring == and != Operators

Now, let's delve into the equal to (==) and not equal to (!=) operators. These become crucial when you need to compare values, such as when comparing the current oxygen level to the desired one:

var currentOxygenLevel = 70  // current oxygen level in %
var requiredOxygenLevel = 100  // required oxygen level in %

var isOxygenEnough = currentOxygenLevel == requiredOxygenLevel  // this results in 'false'
var isOxygenLow = currentOxygenLevel != requiredOxygenLevel  // this results in 'true'

The == operator checks whether the currentOxygenLevel equals the requiredOxygenLevel, yielding a false result. Conversely, the != operator verifies their inequality, returning 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