Using Local Packages in Golang

Sometimes, whilst developing Go libraries, I want to test stuff, but not the correctness; no, I want to test the interface (not related to Go’s interfaces). What does it mean? It means that I want to play with the library to see how it feels to use it.

And since Go has a specific way of handling dependencies, it might not be obvious how to use library B inside the program (or another library, even) A without uploading the code on the network. At least it wasn’t obvious to me.

I’m pretty sure there is a guide somewhere on the Go’s official documentation page, but still… more the merrier.

Actual guide

Imagine our library is called B. We create a directory and initialize the Go module inside of it.

$ cd # just to go to $HOME :)
$ mkdir demo && cd demo
$ mkdir B && cd B
$ go mod init B

Now, we can write a library logic in side of a main.go file.

package b

func Greet(name string) string {
    return "Hi " + name
}

Don’t forget to capitalize functions and variables you want to export :)

Now, we can create a module in which we are going to do the tests and experiments.

$ cd # just to go to $HOME
$ cd demo
$ mkdir A && cd A
$ go mod init A

And after we write our code:

package main

import (
	lib "B"
	"fmt"
)

func main() {
	fmt.Println(lib.Greet("Dante"))
}

There is only one thing left to do:

$ go mod edit -replace B=/home/luka/demo/B
$ go mod tidy
$ go run main.go

Conclusions and closing notes

It wasn’t that hard? There is definitely some getting used to, but it’s manageable.

As per usual, if you find any errors, send me a mail at luka [at] ljudi [dot] org. Cheers!

Previous I'm feeling lucky! Next