为什么Go在项目子目录中找不到导入包?

时间:2019-10-31 19:19:15

标签: go import

当我使用dev_appserver.py启动应用程序时,此导入工作正常

我正在尝试重构以使用Firestore and Go 1.13

app.go内容

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

项目结构:

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

我从工作目录的根目录运行:
$运行* .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)

2 个答案:

答案 0 :(得分:2)

import (
 "workout"
)

这将尝试导入名为workout的stdlib程序包。

要导入workout软件包,应使用go mod init命名主软件包,例如:github.com/me/myapp,然后将workout软件包导入为{{ 1}}。

github.com/me/myapp/workout导入为相对目录(“ ./workout”)也可以,但这不是推荐的方式。

答案 1 :(得分:0)

您的GOPATHGOROOT

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

将工作文件夹移至:

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

更新导入:

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

现在移至:

cd $GOPATH/my-app/

运行app.go

go run app.go