GoLang 101 — (10) Understanding the Basic Math in Go

Handhika Yanuar Pratama
3 min readApr 9, 2024

--

Photo by Chinmay B on Unsplash

Yeah, Day 11

In GoLang, as with many programming languages, you can perform a variety of mathematical calculations using basic arithmetic and unary operators. Here’s a list of them that you’ve likely used in your programs.

The Operators

Addition (+)

Adds two operands.

result := 10 + 5 // result is 15

Subtraction (-)

Subtracts the right operand from the left operand.

result := 10 - 5 // result is 5

Multiplication (*)

Multiplies two operands.

result := 10 * 5 // result is 50

Division (/)

Divides the left operand by the right operand.

result := 10 / 5 // result is 2

Remainder/Modulus (%)

Returns the remainder of the division of the left operand by the right operand.

result := 10 % 3 // result is 1

Unary Plus (+)

Indicates a positive value (usually not necessary as positive values are assumed).

x := +5 // x is 5

Unary Minus (-)

Negates the value of the operand.

x := -5 // x is -5

Increment (++) and Decrement ( — ) Operators

Go does not have traditional ++ and -- operators, instead, you use += 1 or -= 1 respectively for increment and decrement operations.

x := 5
x += 1 // Increment x by 1, x is now 6
x -= 1 // Decrement x by 1, x is now 5 again

Operator Precedence

Operator precedence in Go follows typical rules observed in mathematics. Multiplication and division have a higher precedence than addition and subtraction. Parentheses can be used to override precedence.

result := 10 + 5 * 2 // result is 20, not 30
result := (10 + 5) * 2 // result is 30

The Code

Here I already combined all the code before into one program.

package main

import "fmt"

func main() {
// Basic Arithmatic
result1 := 10 + 5
result2 := 10 - 5
result3 := 10 * 5
result4 := 10 / 5
result5 := 10 % 5

fmt.Println("Result1: ", result1)
fmt.Println("Result2: ", result2)
fmt.Println("Result3: ", result3)
fmt.Println("Result4: ", result4)
fmt.Println("Result5: ", result5)

// Unary Operator
x := +5
y := -5

fmt.Println("x: ", x)
fmt.Println("y: ", y)

// Increment and Decrement
xx := 5
xx += 1
fmt.Println("xx: ", xx)

yy := 10
yy -= 1
fmt.Println("yy: ", yy)

// Precedence
result6 := 10 + 5*2
reuslt7 := (10 + 5) * 2

fmt.Println("result6: ", result6)
fmt.Println("result7: ", reuslt7)
}

So, the results are this.

Positive unary is actually optional, you don’t have to used it every time, because, by default, every integer we put in, will always positive.

Conclusion

With these operators, you can handle a wide range of mathematical operations efficiently and effectively. Additionally, being aware of operator precedence ensures that your calculations produce the expected results. Thanks for reading.

--

--

Handhika Yanuar Pratama
Handhika Yanuar Pratama

Written by Handhika Yanuar Pratama

Live the Way the Life ask for || A Stoic Engineer || Technical Writer || Runner x Dreamer

No responses yet