DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

Go - package is not in GOROOT

#go

The below error occurred when I had changed GOPATH, made two packages, and written some codes.

% package other/pkg1 is not in GOROOT (/usr/local/go/src/other/pkg1)
Enter fullscreen mode Exit fullscreen mode

The cause is a package structure. Putting it together solves it.

Error

Below is the directory structure when the error occurred.

${GOPATH}/src
|-- other
|   |-- go.mod
|   `-- pkg1
|       `-- pkg1.go
`-- prj
    |-- go.mod
    `-- main.go
Enter fullscreen mode Exit fullscreen mode

prj package is unable to refer to other/pkg1 although it is in GOPATH.

Codes are below.

prj/main.go

package main

import "other/pkg1"

func main()  {
    pkg1.Func()
}
Enter fullscreen mode Exit fullscreen mode

other/pkg1/pkg1.go

package pkg1

import "fmt"

func Func() {
    fmt.Println("called func in pkg1")
}
Enter fullscreen mode Exit fullscreen mode

Fix

To include other in prj solves the error.

${GOPATH}/src
`-- prj
    |-- go.mod
    |-- main.go
    `-- other
        `-- pkg1
            `-- pkg1.go
Enter fullscreen mode Exit fullscreen mode

prj/main.go

package main

import "prj/other/pkg1"

func main()  {
    pkg1.Func()
}
Enter fullscreen mode Exit fullscreen mode

Latest comments (3)

Collapse
 
t0nghe profile image
Tonghe Wang • Edited

I met a similar problem.

When the issue happened, my folder structure looked like this:

dbmock/
├── dbmock.go
├── go.mod # §
├── go.sum
└── internal/
    └── dbconn/
        ├── dbconn.go
        └── go.mod # ¶
Enter fullscreen mode Exit fullscreen mode

I got an error message that says:

package dbmock/internal/dbconn is not in GOROOT (/usr/local/go/src/dbmock/internal/dbconn)

After some experimenting, I realized what I did wrong was go mod init at /internal/dbconn. I only needed to initialize a module at dbmock/.

By removing internal/dbconn/go.mod (¶) and only keeping dbmock/go.mod (§), it is working fine now.

For your reference, import section in dbmock.go looks like this now:

package main

import (
    db "dbmock/internal/dbconn"
)

func main() {
    db.InitDb()
//...
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ouzsrcm profile image
ouzsrcm • Edited

i have the same problem. but i can't fix it.
error: main.go:5:2: package lessons/lesson1/util is not in GOROOT (C:\Program Files\Go\src\lessons\lesson1\util)

proj: dev-to-uploads.s3.amazonaws.com/up...

Collapse
 
takakd profile image
Takahiro Kudo

Thank you for your feedback. I don't know the matter why the error happens right now. I'll check that.💪