Working with Functions in Go

11.05.2021

Intro

Function allow you to group code together and easily reuse code. In Go, we always have a main function where the program starts. From then on, we can build out functions to keep our code reusable and to easily repeat procedures. In this article, we will learn how to use functions in Go.

Functions in Go

Declaring function in go has the following format

func functionName(parameter1) int {
   // body of the function
}

We have the following components.

  • func keyword that starts the declaration
  • functionName that is a name we choose and will use to call the function
  • (parameter1) a place to put our parameters or inputs. This can be 0, 1, or many as we will see
  • int the return type of our function. In this case, we return an integer
  • {} brackets to surround the code we want to reuse

Our First Function

Let's start with a simple example. We will create a function to add two numbers together.

func add(num1 int, num2 int) int {
   return num1 + num2
}

Notice that we have added types to our parameters, so a user of this function will have to pass in 2 integers. We also add a return keyword so the function will return the result of the 2 numbers.

Let's call our function like so.

result = add(3, 4)

The Full Example

Now, let's create an open up a file call main.go and paste the following code.

package main

import "fmt"

func add(num1 int, num2 int) int {
	return num1 + num2
}

func main() {
	result := add(1, 2)

	fmt.Printf("result: %d \n", result)
}

We can run the program by using the following command: go run main.go.