How to use a module that is outside of "GOPATH" in another module?

Run:

go mod init yellow

Then create a file yellow.go:

package yellow

func Mix(s string) string {
   return s + "Yellow"
}

Then create a file orange/orange.go:

package main
import "yellow"

func main() {
   s := yellow.Mix("Red")
   println(s)
}

Then build:

go build

https://golang.org/doc/code.html


The easiest and working out-of-the-box solution is to put your database package / module into a VCS (e.g. github.com), so other packages (inside other modules) can simply refer to it by importing it like:

import "github.com/someone/database"

If you do so, you don't even have to fiddle with the go.mod files manually, everything will be taken care of by the go tool: it will automatically recognize and resolve this dependency, download and install the required package, and will also update go.mod automatically.

Staying entirely on local disk

If you don't want to use a VCS (e.g. you're just experimenting or you haven't decided what to use yet), then you can still do it. The how is detailed in the official Go Wiki: Can I work entirely outside of VCS on my local filesystem?

So you created a database folder outside of GOPATH, and you created a module in it. And you created another module, let's call it main, and you want to use this database package.

What you must do is:

  • go.mod of your main module must list the database package as a "requirement". Give a temporary VCS name to your database package:

    require (
        example.com/me/database v0.0.0
    )
    
  • You must tell the go tool where this package is located, because the full package name we used is just a temporary / fantasy name. Use the replace directive to make this database package point to a folder on your local disk; you may use absolute and relative paths:

    replace example.com/me/database => ../database
    

And that's all.

Working example

Let's see a working example. Let's create a pretty module. Create a pretty folder with 2 files in it:

pretty.go:

package pretty

import "fmt"

func Pretty(v ...interface{}) {
    fmt.Println(v...)
}

go.mod (can be created by running go mod init pretty):

module pretty

Now let's create another, main module. Let's create a folder osinf (it may be whatever) next to the pretty folder. 2 files in it:

osinf.go (note we intend to use our pretty package / module, we import it by "example.com/me/pretty"):

package main

import "example.com/me/pretty"

func main() {
    pretty.Pretty("hi")
    pretty.Pretty([]int{1, 3, 5})
}

go.mod:

module main

require example.com/me/pretty v0.0.0

replace example.com/me/pretty => ../pretty

And that's all.

Running go run osinf.go in the osinf folder, the output is:

hi
[1 3 5]

Tags:

Go

Go Modules