Functions

Functions

What is a Function?

A function is a block of code that performs a specific task. It takes input, processes it, and returns an output. For example, a function might calculate the area of a circle when given its radius.

Function Declaration

The syntax for declaring a function in Go is:

func functionname(parametername datatype) returntype {
    // function body
}        

  • func: The keyword used to declare a function.
  • functionname: The name of the function.
  • parametername datatype: The parameters the function takes.
  • returntype: The type of value the function will return (can be omitted if no return value).

Example: Simple Function

Here’s a function that calculates the total price by multiplying price and quantity:

func calculateBill(price, quantity int) int {
    var totalPrice = price * quantity
    return totalPrice
}        

  • This function takes price and quantity as inputs and returns the totalPrice as an integer.

Calling a Function

To call a function, use its name followed by the parameters in parentheses ():

calculateBill(10, 5)        

Here’s the complete program:

package main

import "fmt"

func calculateBill(price, quantity int) int {
    var totalPrice = price * quantity
    return totalPrice
}

func main() {
    price, quantity := 90, 6
    totalPrice := calculateBill(price, quantity)
    fmt.Println("Total price is", totalPrice)
}        

Output:

Total price is 540        

Multiple Return Values

Go allows functions to return multiple values. For example, to calculate both the area and perimeter of a rectangle:

func rectProps(length, width float64) (float64, float64) {
    var area = length * width
    var perimeter = (length + width) * 2
    return area, perimeter
}        

  • The function returns both area and perimeter of type float64.

Example usage:

package main

import "fmt"

func rectProps(length, width float64) (float64, float64) {
    var area = length * width
    var perimeter = (length + width) * 2
    return area, perimeter
}

func main() {
    area, perimeter := rectProps(10.8, 5.6)
    fmt.Printf("Area %f Perimeter %f", area, perimeter)
}        

Output:

Area 60.480000 Perimeter 32.800000        

Named Return Values

You can assign names to return values in a function. This allows you to return them implicitly without explicitly mentioning them in the return statement.

func rectProps(length, width float64) (area, perimeter float64) {
    area = length * width
    perimeter = (length + width) * 2
    return
}        

  • area and perimeter are named return values, so return automatically returns them.

Blank Identifier (_)

In Go, _ is used as the blank identifier. It is used when you want to discard a returned value. For example, if you only need the area and not the perimeter from the rectProps function:

package main

import "fmt"

func rectProps(length, width float64) (float64, float64) {
    var area = length * width
    var perimeter = (length + width) * 2
    return area, perimeter
}

func main() {
    area, _ := rectProps(10.8, 5.6)  // Discard perimeter
    fmt.Printf("Area %f ", area)
}        

Output:

Area 60.480000        

Summary

In this tutorial, we learned how to declare and use functions in Go. Functions can return single or multiple values, and Go’s strong typing ensures that types are handled explicitly. We also explored named return values and the use of the blank identifier to discard unused values.

Next tutorial: Packages

To view or add a comment, sign in

More articles by Nin Tran

  • Why Microservices are Beating Monoliths in Modern Software Development

    In today’s fast-moving tech world, building software that is scalable, resilient, and easy to evolve is more important…

  • The 5 Key Scrum Ceremonies You Should Know

    In the Scrum framework, effective communication and continuous improvement are driven by five essential ceremonies: 1…

    1 Comment
  • Key Kubernetes Concepts – A Concise Overview for Engineers

    Kubernetes has become the backbone of modern cloud-native infrastructure. For teams building and scaling containerized…

  • Switch Statement

    In Go, the switch statement is a powerful tool for performing multiple comparisons against a single expression. It is…

  • Loops

    In Go, loops are used to execute a block of code repeatedly until a specified condition is met. The only loop available…

  • 🚀 How I Set Up My Mac Terminal (Every Time I Get a New Machine)

    Recently, our IT team reinstalled my Mac — which reminded me how often I end up redoing my terminal setup from scratch.…

    1 Comment
  • Object-Oriented Go: Applying OOP Principles in the Go Programming Language

    Object-Oriented Programming (OOP) has shaped the way we build software for decades. Centered around "objects" —…

  • If else statement

    What is an If Statement? In Go, an if statement checks a condition and executes a block of code if the condition…

  • Packages

    What are Packages? Packages in Go are used to organize code into modular components. They allow for better code reuse…

  • Constant in Golang

    What is a Constant? Constants represent fixed values that do not change throughout the program’s execution. Examples…

Explore content categories