简体   繁体   中英

Why Go can't find import package in project subdirectory?

This import worked fine when I was starting app with dev_appserver.py

I am trying to refactor to use Firestore and Go 1.13

app.go content

package main
import (
    "net/http"
    "workout"
)

Project structure:

app.go  
|-- workout dir  
    |-- workout.go file that contains (package workout)  

From the root of the Working Directory I ran:
$ go run *.go

app.go:15:2: cannot find package "workout" in any of:
    /usr/local/go/src/workout (from $GOROOT)
    /Users/X/go/src/workout (from $GOPATH)
$ go run *.go workout/*.go
named files must all be in one directory; have ./ and workout/
X@MacBook-Pro Thu Oct 31 10:48:13 ~/Dropbox/go/src/workoutNew 
$ go build   
app.go:15:2: cannot find package "workout" in any of:
    /usr/local/go/src/workout (from $GOROOT)
    /Users/X/go/src/workout (from $GOPATH)
import (
 "workout"
)

This will try to import a stdlib package called workout .

In order to import your workout package, you should name your main package (using go mod init ), like: github.com/me/myapp , then import the workout package as github.com/me/myapp/workout .

Importing workout as a relative directory ( "./workout") also works, but that is not the recommended way of doing it.

Your GOPATH and GOROOT :

/usr/local/go/src/workout (from $GOROOT)
/Users/X/go/src/workout (from $GOPATH)

Move your working folder under:

$GOPATH/my-app/
my-app
|...app.go
    workout
    |...workout.go

Update import:

package main
import (
    "net/http"
    "my-app/workout"
)

Now move to:

cd $GOPATH/my-app/

Run app.go :

go run app.go

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM