If-Else Statements

2-minute read
Table of Contents

We can have sections run only if a certain condition or conditions is/are satisfied. This can be achieved using if-else statements. Consider the following code:

package main

import "fmt"

func main() {
	age := 19
	if age >= 18 {
		fmt.Printf("You are an adult\n")
	} else {
		fmt.Printf("You are not old enough\n")
	}
}
if-adult.go
Copy

The condition we use here is a check to see if the age is greater than or equal to (coded as >=) the value of $18$. If the age is at least $18$, the program will print “You are an adult” onto the console. If not, it will print “You are not old enough”. Try changing the age to $14$ and re-running the code.

We can use many other relational operators such as less than (<), greater than (>), less than or equal to (<=), equal to (==).

Notice that the assignment operator (=) is different from the “equals to” comparison operator (==). The former is used to assign a new value to a variable whereas the latter is used to check if two values are the same.

Use if alone

We do not need have an else portion for an if-else statement. Sometimes, we only want to check for one condition and do nothing if the condition is not satisfied:

package main

import "fmt"

func main() {
	if 5 < 3 {
		fmt.Printf("5 is less than 3")
	}
}
if-less-than.go
Copy

This code will output nothing as the condition (if 5 is less than 3) is not satisfied.

Logical operators

We can combine multiple conditions together using the logical AND (&&) and logical (||) operators. We can also invert the truth value of a condition by using the logical NOT (!) in front of the condition itself:

package main

import "fmt"

func main() {
	age := 20
	height := 100
	pin := 2002

	if age > 13 && height > 80 {
		fmt.Printf("You can go on the ride\n")
	}

	if pin == 2002 || 9 < 8 {
		fmt.Printf("Phone unlocked\n")
	}

	if !(age < 13) {
		fmt.Printf("You aren't a kid anymore\n")
	}
}
logical-operators.go
Copy

The code above will print 3 statements. What some values for age, height and pin would ensure that none of the print statements are executed?

Support us via BuyMeACoffee