Skip to main content
Published on

Arithmetic Operators in Go

Share:

Introduction

Arithmetic operations are the backbone of any program, enabling calculations and processing logic. Go, with its clear syntax and optimized performance, provides a complete set of arithmetic operators that are intuitive to use.

Basic Arithmetic Operators

Here are the main arithmetic operators you'll encounter in Go:

  • + | Addition
  • - | Subtraction
  • * | Multiplication
  • / | Division
  • % | Remainder (or Modulo)
package main

import "fmt"

func main() {
	fmt.Println("Addition:", (10 + 10))
	fmt.Println("Subtraction:", (10.5 - 5.5 - 4.5))
	fmt.Println("Multiplication:", (-10 * 2))
	fmt.Println("Division:", (10 / 2))
	fmt.Println("Remainder:", (8 % 3))
}

Nuances and Quirks

Division by Zero

In many languages, dividing by zero leads to a runtime error. In Go, dividing an integer by zero causes the program to panic, while dividing a float by zero will result in infinity.

Remainder or Modulo

The modulo or remainder operation is frequently used in programming problems. In Go, it is represented by the % symbol. This operator returns the remainder of the division of two numbers. For example, 5 % 3 will return 2.

Operator Precedence

As in many languages, Go has rules about the order in which operators are evaluated, known as operator precedence. Multiplication and division take precedence over addition and subtraction. To ensure a specific order of evaluation, use parentheses.

Practicing with Arithmetic Operators

Arithmetic operators are essential for any kind of calculation, from simple math to complex algorithms. I encourage you to play around with these operators in different scenarios to solidify your understanding.

Happy coding!