HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoMajor

Accessing local packages within a go module (go 1.11)

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
modulepackagesaccessinglocalwithin

Problem

I'm trying out Go's new modules system and am having trouble accessing local packages. The following project is in a folder on my desktop outside my gopath.

My project structure looks like:

/
  - /platform
      - platform.go
  - main.go
  - go.mod


// platform.go
package platform

import "fmt"

func Print() {
    fmt.Println("Hi")
}


// main.go
package main

import "platform"

func main() {
    platform.Print()
}


go build main.go tells me

cannot find module for path platform

Solution

I would strongly suggest you to use go toolchain which takes care of these issues out of the box. Visual Studio Code with vscode-go plugin is really useful.

Problem here is that Go requires relative paths with respect to your $GOPATH/src or module in import statement. Depending on where you are in your GOPATH, import path should include that as well. In this case, import statement must include go module path in go.mod

GOPATH

Assume your project resides here:

$GOPATH/src/github.com/myuser/myproject


Your import path should be:

import "github.com/myuser/myproject/platform"


VGO

Assume your go.mod file is:

module example.com/myuser/myproject


Your import path should be:

import "example.com/myuser/myproject/platform"

Code Snippets

$GOPATH/src/github.com/myuser/myproject
import "github.com/myuser/myproject/platform"
module example.com/myuser/myproject
import "example.com/myuser/myproject/platform"

Context

Stack Overflow Q#52026284, score: 65

Revisions (0)

No revisions yet.