Creating your own package in Go

When we import a library in Go we’re really importing a package. A package is created in a folder of it’s own and whilst you can name the folder anything you like, by convention we should name the folder the same as the package name that the files within the folder will be part of.

For example if our project is in the folder src/example and we want to create a package called conv (for converters) then this should be created in src/example/conv.

The files within this folder can be named anything you like and can have any package names, for example the Go source has a package context and it includes files as part of the package context but also package context_test, but ofcourse it makes sense that the code is all relevant to the package/folder it’s contained within – for example tests etc. might have a different package name to not pollute the package that the user/dev sees.

Let’s create a simple Echo function in a package named test, so off of our main.go folder we create a test folder and within this we have a test.go file and here’s the source

package test

func Echo(s string) string {
	return s
}

to use this package in our main.go file we import like this

package main

import "fmt"
import "Example/test"

func main() {
	fmt.Println(test.Echo("Hello"))
}

Notice the Example/test (our project name in Gogland) followed by the package folder name. The Example folder in this case is the folder that our main.go file is within.

References

How to Write Go Code contains a great overview of project, folder and package layouts for your Go application.