Joel Dare

Writing Packages in Go

In your main go program you can import the package you want to write. In this code we’re going to include an example package and then we call it’s Print function.

See my go-package-example git repo for the full code to this example.

package main

import (
	"example/example"
)

func main() {
	example.Hello()
}

Here’s what the example package looks like.

package example

import "fmt"

func Hello() {
	fmt.Println("hello world")
}

You need to make sure you have a go.mod file for your main project, which will contain something like the following.

module example

go 1.19

So, here’s the file structure you end up with.

example
  hello.go
main.go
go.mod

Now run it with the following command.

go run main.go

You can also reference your local package using a remote package name with something like this in your go.mod file.

replace (
    "github.com/user/example" => "/home/user/sandbox/example"
)

Written in Nolific by Joel Dare on 04/19/2023