Gregory Trubetskoy

Notes to self.

Relative Imports Hack in Golang

| Comments

If you have multiple packages in your program’s Go source code, you probably have come across a situation where if you create a fork on Github or move/rename your top level directory, all your import statements need to be adjusted.

There is a simple hack to accomplish relative imports by using the vendor directory and symlinks. If you have a package directory called mypkg, then the following should work:

1
2
$ mkdir -p vendor/relative
$ ln -s ../../mypkg vendor/relative/mypkg

And now, your Go code could do this:

1
2
3
4
5
6
7
package main

import (
    "fmt"

    "relative/mypkg"
)

I cannot think of any downsides to this approach, if you know of any, please do comment!

Comments