Go, also known as Golang, is a statically typed, compiled programming language designed by Google. It’s known for its simplicity and efficiency. In this article, we'll cover how to perform basic arithmetic operations in Go.
Arithmetic Operators
Like most programming languages, Go provides operators to perform arithmetic operations. The basic arithmetic operators are:
+for addition-for subtraction*for multiplication/for division%for modulus (remainder of division)
Basic Example
Let's start with an example of using these operators in Go:
package main
import "fmt"
func main() {
a := 20
b := 10
fmt.Println("Addition:", a + b)
fmt.Println("Subtraction:", a - b)
fmt.Println("Multiplication:", a * b)
fmt.Println("Division:", a / b)
}
Output:
Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2
Intermediate Example
Now, let's perform these operations in functions that can be reused:
package main
import "fmt"
func add(x int, y int) int {
return x + y
}
func subtract(x int, y int) int {
return x - y
}
func multiply(x int, y int) int {
return x * y
}
func divide(x int, y int) int {
if y == 0 {
fmt.Println("Division by zero")
return 0
}
return x / y
}
func main() {
a, b := 20, 10
fmt.Println("Addition:", add(a, b))
fmt.Println("Subtraction:", subtract(a, b))
fmt.Println("Multiplication:", multiply(a, b))
fmt.Println("Division:", divide(a, b))
}
Advanced Example
In the advanced example, we will take input from the user for two numbers and the operation they want to perform:
package main
import (
"fmt"
"os"
"bufio"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter first number: ")
firstInput, _ := reader.ReadString('\n')
firstInput = strings.TrimSpace(firstInput)
a, err1 := strconv.Atoi(firstInput)
if err1 != nil {
fmt.Println("Invalid input")
return
}
fmt.Print("Enter second number: ")
secondInput, _ := reader.ReadString('\n')
secondInput = strings.TrimSpace(secondInput)
b, err2 := strconv.Atoi(secondInput)
if err2 != nil {
fmt.Println("Invalid input")
return
}
fmt.Print("Enter operation (+, -, *, /): ")
operation, _ := reader.ReadString('\n')
operation = strings.TrimSpace(operation)
switch operation {
case "+":
fmt.Println("Result:", a+b)
case "-":
fmt.Println("Result:", a-b)
case "*":
fmt.Println("Result:", a*b)
case "/":
if b == 0 {
fmt.Println("Cannot divide by zero")
} else {
fmt.Println("Result:", a/b)
}
default:
fmt.Println("Unknown operation")
}
}