At first glance Golang appears to dislike having any sort of folder structure. This is because code is automatically shared within the same project. Let's say we have two files as follows:
//main.go
package main
import "fmt"
func main() {
result := calculateTotal(1,3)
fmt.Println(result) //4
}
//calculate.go
package main
func calculateTotal(nums ...int) int {
total := 0
for _, num := range nums {
total += num
}
return total
}
Our main file has access to the calculateTotal function because both files are in the main
package. If you're unsure about the ...
notation in calculateTotals check out my article explaining it.
Currently these are the only two files in our project and there are no folders. You could see how very quickly our file list could get disorganised, and it would be desirable to add folders.
Let's put calculate in it's own folder.
The reason it doesn't like this is that all files in a package need to be in the same directory. Since we moved the function, it cannot find it any more. Let's resolve the issue.
First we need to change the package name for calculate. It makes sense to have the package match the folder name:
//calculate/calculate.go
package calculate
func CalculateTotal(nums ...int) int {
Note that we also made the function name uppercase. This is to signify to Go that we want to export this function so that it will be accessible when someone imports the package.
Next we need to add a go.mod
file and declare the module for our project.
//go.mod
module example
go 1.17
I've just called it example
and declared the version of go that I'm using.
Finally to make our project work again, we need to import the project intomain.go
package main
import (
"example/calculate"
"fmt"
)
func main() {
result := calculate.CalculateTotal(1,3)
fmt.Println(result) //4
}
If you're having issues with your import statement disappearing when you save, it's likely that you've forgotten to capitalise theCalculateTotal
function in both files.
Note that the module name is used in the import.
The last thing that I would do here is change the name of the function so that it reads a little nicer when it's imported. I'd probably change it tototal
so that when we import it, it reads calculate.total(1,3)
.
Self taught software developer with 11 years experience excelling at JavaScript/Typescript, React, Node and AWS.
I love learning and teaching and have mentored several junior developers over my career. I find teaching is one of the best ways to solidify your own learning, so in the past few years I've been maintaining a technical blog where I write about some things that I've been learning.
I'm passionate about building a teams culture and processes to make it efficient and satisfying to work in. In many roles I have improved the quality and reliability of the code base by introducing or improving the continuous integration pipeline to include quality gates.