Conditionals in Go (challenge answer)

devdrake0

Si

Posted on June 26, 2019

Conditionals in Go (challenge answer)

Conditionals in Go (challenge answer)

At the end of the last article ( "Conditionals in Go" ), we said it was possible to optimise the if/else if/else statement further and gave you the challenge of figuring out how. If you haven't attempted it; we're about to give you the answer, so now's a good time to go and try it.

For reference, here was the if/else if/else statement we said could be optimised:

if age < 13 {
  log.Println("I am considered a child")
} else if age >= 13 && age < 20 {
  log.Println("I am considered a teenager")
} else if age >= 20 && age < 70 {
  log.Println("I am considered an adult")
} else {
  log.Println("I am considered a pensioner")
}

It can be optimised further because we're still doing more checks than we need to. The following diagram shows the flow of this conditional statement:

Conditionals in Go (challenge answer)

For example, we're checking if age is less than thirteen ( age < 13 ) and, if it is, we print the "child" statement and end the conditional statement. If it isn't, we then check if age is greater than or equal to thirteen ( age >= 13 ).

This extra step is unnecessary because we've already checked if age is less than thirteen and, if it isn't, then it has to be equal to or greater than thirteen.

Knowing this, we can simplify the flow of our conditional statement to the following:

Conditionals in Go (challenge answer)

And therefore our if/else if/else statement becomes:

if age < 13 {
  log.Println("I am considered a child")
} else if age < 20 {
  log.Println("I am considered a teenager")
} else if age < 70 {
  log.Println("I am considered an adult")
} else {
  log.Println("I am considered a pensioner")
}

If this isn't clear, feel free to reach out to us and we'll do what we can to help you.


CodeTips strives to help beginners, with zero or very little experience, learn to code.

We do cross-post to other sites to reach a wider audience, but why not subscribe to our newsletter and get the newest articles straight to your mailbox?

The original source for this content is CodeTips. The original content is kept up-to-date, but other sources may not be the latest version.

💖 💪 🙅 🚩
devdrake0
Si

Posted on June 26, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Two Sum
beginners Two Sum

December 28, 2019

Table Driven Tests
beginners Table Driven Tests

December 16, 2019

Structs in Go (challenge answer)
beginners Structs in Go (challenge answer)

August 21, 2019

Structs in Go
beginners Structs in Go

July 15, 2019

Functions in Go (challenge answer)
beginners Functions in Go (challenge answer)

July 15, 2019