Go Tutorial menu

Go Operators and Conditions

Operators work with values, and conditions decide which code runs.

Arithmetic Operators

OperatorNameExampleResult
+Add11 + 415
-Subtract11 - 47
*Multiply11 * 444
/Divide11 / 42
%Remainder11 % 43

Example

go
package main

import "fmt"

func main() {
	fmt.Println(11 / 4)
	fmt.Println(11.0 / 4)
	fmt.Println(11 % 4)

	balance := 800
	balance += 200
	balance -= 150
	balance++
	fmt.Println(balance)
}
Output
2
2.75
3
851

Dividing two whole numbers gives a whole number. In Go, x++ is a statement on its own line; you cannot write y := x++.

Comparison and Logical Operators

Comparison operators return true or false: ==, !=, >, <, >=, <=.

Logical operators combine conditions:

  • && (and): both must be true
  • || (or): at least one must be true
  • ! (not): reverses the value

if and else

Go does not use brackets around the condition, but the curly braces are always required.

Example

go
package main

import "fmt"

func main() {
	marks := 67

	if marks >= 80 {
		fmt.Println("Grade A")
	} else if marks >= 60 {
		fmt.Println("Grade B")
	} else {
		fmt.Println("Grade C")
	}

	age := 22
	hasCard := false
	if age >= 18 && !hasCard {
		fmt.Println("Please apply for your ID card")
	}
}
Output
Grade B
Please apply for your ID card

The else must be on the same line as the closing } of the if. Putting it on a new line is a compile error in Go.

if with a Short Statement

You can run a short statement before the condition. The variable created there exists only inside the if and else blocks.

Example

go
package main

import "fmt"

func main() {
	price := 1200
	if total := price * 3; total > 3000 {
		fmt.Println("Free delivery on Rs", total)
	} else {
		fmt.Println("Delivery charge applies on Rs", total)
	}
}
Output
Free delivery on Rs 3600

switch

switch checks a value against several cases. Go runs only the matching case, so you do not need break.

Example

go
package main

import "fmt"

func main() {
	day := "Friday"
	switch day {
	case "Saturday", "Sunday":
		fmt.Println("Weekend")
	case "Friday":
		fmt.Println("Short day, Jummah prayers")
	default:
		fmt.Println("Normal working day")
	}

	temp := 36
	switch {
	case temp > 40:
		fmt.Println("Extreme heat")
	case temp > 30:
		fmt.Println("Hot")
	default:
		fmt.Println("Pleasant")
	}
}
Output
Short day, Jummah prayers
Hot
switch featureExample
Several values in one casecase "Saturday", "Sunday":
Default casedefault:
No value after switchWorks like an if / else if chain
fallthroughContinues into the next case (rarely used)

Exercise

Exercise

What does fmt.Println(17 / 5) print in Go?

Learn Go with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp