小编典典

go中如何导入本地包?

all

我是新手,正在编写一个我想本地化的示例代码。

在原始main.go导入语句中是:

 import (
    "log"
    "net/http"
    "github.com/foo/bar/myapp/common"
    "github.com/foo/bar/myapp/routers"
)

现在我有commonrouters打包/home/me/go/src/myapp

所以我将导入语句转换为:

import (
    "log"
    "net/http"
    "./common"
    "./routers"
)

但是当我运行时,go install myapp我得到了这些错误:

can't load package: /home/me/go/src/myapp/main.go:7:3: local import "./common" in non-local package

此外,当我在 import 语句中使用commonandrouters而不是./commonand时,我得到:./routers

myapp/main.go:7:3: cannot find package "common" in any of:
    /usr/local/go/src/common (from $GOROOT)
    /home/me/go/src/common (from $GOPATH)
myapp/main.go:8:2: cannot find package "routers" in any of:
    /usr/local/go/src/routers (from $GOROOT)
    /home/me/go/src/routers (from $GOPATH)

我怎样才能解决这个问题?


阅读 144

收藏
2022-08-21

共1个答案

小编典典

好吧,我发现了问题所在。基本上去导入的起始路径是$HOME/go/src

所以我只需要myapp在包名前面加上,也就是import应该是:

import (
    "log"
    "net/http"
    "myapp/common"
    "myapp/routers"
)
2022-08-21