Export Function in Golang

Learn via video courses
Topics Covered

Overview

In this tutorial, you will learn how to export a golang function that you can use in another package. We will discuss why it is required, why it is a good practice, and when not to use it.

Why Export a Function?

The basic rule of 101 programming is modularity and reusability. Using modularity, you break down a feature into smaller tasks, and using reusability, you reuse the same functionality at multiple places.

By exporting the function, you can achieve reusability.

In golang, by default the scope of a function is limited to the package it is defined. To access a function in another package, you have to explicitly export it.

In golang, there is no special keyword required to export a function. Golang exports a function if its name's first letter is Uppercase.

Export a Function in Golang

Create a project directory structure as below:

Create an area/area.go file. This file contains a function to calculate the area of a circle.

Create a main.go file. This is the entry point of the program. From here you will try to access areaOfCircle.

Run the program:

You will notice it will throw an error as area.areaOfCircle is undefined.

Now change the function name to uppercase AreaOfCircle.

Run the program:

This time it will run and return the output.

Examples

Exporting using uppercase the first letter is not limited to the function, you can even export a struct and a variable. In short, anything which starts with an uppercase is an export.

Export a Variable

Let's follow the same directory structure and example. We will create a constant variable Pie and print its value in main.go.

Update area.go.

Update main.go

Output:

In this example, we created a constant variable Pie and printed its value in main.go.

Export a Struct

In this example, we will create a Rectangle struct and a function to calculate its area.

Update area.go

Update main.go

Output:

Remember in this example, the name of the struct and its fields', the first letter is in Uppercase.

Conclusion

In this tutorial, we learned how to export a function to make code reusable. We learned, in golang, there is no special keyword required to export a function. By Uppercasing the first letter of a function it exports.