DMarlon Studio

Lesson 6 · 6 of 20

If and else · Go

Make decisions in Go with if, else if and else, combine conditions with &&, || and !, and use the if statement's init part.

Go · If and else in DMarlon Studio: the example's code and its output in the terminal

if runs its block only when the condition is true. In Go the condition has no parentheses, but the braces are required, even for a single line. else if tries another condition and else catches everything else: at 31 degrees the first one holds, and the others are not even checked.

Conditions combine with && (and), || (or) and ! (not). age >= 18 && hasTicket needs both; since age is 17, it fails and Go moves on to hasTicket && !(age < 16): there is a ticket and the person is not under 16, so they get in with an adult.

Go allows an init statement before the condition, separated by a semicolon: if total := price * float64(units); total >= 50. It works out total first and then compares it. That variable only exists inside the if and its else branches, so no leftover variables hang around.

At 18.5 euros for 3 units, total is 55.5, more than 50, so shipping is free. This form is very common in Go for checking errors, as you will see in lesson 13: if err := ...; err != nil.

Code · main.go

package mainimport "fmt"func main() {	temperature := 31	// The condition needs no parentheses, but the braces are required.	if temperature > 30 {		fmt.Println("It is hot: drink water")	} else if temperature > 15 {		fmt.Println("Nice weather for a walk")	} else {		fmt.Println("Take a coat")	}	// && (and), || (or) and ! (not) combine conditions.	age, hasTicket := 17, true	if age >= 18 && hasTicket {		fmt.Println("Welcome to the concert")	} else if hasTicket && !(age < 16) {		fmt.Println("Welcome, with an adult")	} else {		fmt.Println("Sorry, no entry")	}	// An init statement runs first; total only exists inside this if.	price, units := 18.5, 3	if total := price * float64(units); total >= 50 {		fmt.Printf("Total %.2f: free shipping\n", total)	} else {		fmt.Printf("Total %.2f + 4.95 shipping\n", total)	}}

Output · go run main.go

It is hot: drink water
Welcome, with an adult
Total 55.50: free shipping

Key points

  • No parentheses around the condition; braces are required.
  • else if chains conditions; else catches the rest.
  • && is "and", || is "or" and ! is "not".
  • if x := ...; condition declares a variable just for that if.

Exercise

Change units to 2 and check that shipping is charged. Then add an else if for orders of 30 euros or more, with shipping at 2.95.