go

Why does the run command cannot find my custom package at $GOPATH/src?


I have two go source files:

  1. $GOPATH/src/greeting/greeting.go
  2. $GOPATH/src/hi/main.go

Here's the contents of main.go:

package main

import "greeting"

func main() {
  greeting.Hello()
  greeting.Hi()
}

Here's the contents of greeting.go:

package greeting

import "fmt"

func Hello() {
  fmt.Println("Hello!")
}

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

When I invoke the following commmand: go run main.go

from the following path: $GOPATH/src/hi

I get the following error: main.go:4:2: package greeting is not in std (/usr/lib/go/src/greeting)

Why is it not looking in my $GOPATH pointing to: /home/thesevs/Workspace/go


Solution

  • There's an environment variable called GO111MODULE where it decies go command should run in manages module-aware mode or not. It came with Go 1.11 and it's enabled by default as of Go 1.16.

    If this environment variable's value is off as follows

    then the go command runs in GOPATH mode.

    However, in your case it looks for GOROOT which is /usr/local/go/src and since there's no greeting package it gives you an error.

    Therefore, to force Go to run in GOPATH mode you should set "GO111MODULE"s value as off.

    Most probably in your system its value is either "on" or unset.

    you can try running below;

    GO111MODULE=off go run main.go
    

    p.s. you can check the value of the environment variable using "go env"