Unlock Your Python Backend Career: Build 30 Projects in 30 Days. Join now for just $54

Go Essentials

Functions in Go

In Go, functions are treated as first-class citizens, allowing you to pass them as arguments, return them from other functions, and even create anonymous functions.

The Go compiler automatically recognizes the main function we have used as the entry-point function where all relevant functions and operations are carried out. 

By the rule of thumb, a project that must be built must have a main function. 

Let's see how other functions are written. Below is a basic function that has an input, an output, and a body. Here's an example:

package main

import "fmt"

// add accepts two input parameters of type int, and returns a single output of type int.
func add(a, b int) int {
    return a + b
}

func main() {
		// add function is called and used here.
    result := add(10, 20)
    fmt.Println("Sum:", result) // Output: Sum: 30
}

Just so you know, a function with output specified must have a return statement by the rule of thumb. Also, when calling a function, you must satisfy its required number of parameters to use it.

In Go, you can assign functions to variables and use them like any other variable. This is particularly useful when passing functions as arguments to other functions. In this example, we use a function variable to calculate the area of a rectangle:

package main

import "fmt"

type calculate func(float64, float64) float64

func rectangleArea(length, width float64) float64 {
    return length * width
}

func main() {
    var area calculate
    area = rectangleArea

    length, width := 5.0, 10.0
    result := area(length, width)

    fmt.Printf("Rectangle Area with length %.2f and width %.2f: %.2f\n", length, width, result)
    // Output: Rectangle Area with length 5.00 and width 10.00: 50.00
}

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board