如何在go中导入本地包? [英] How to import local packages in go?

查看:46
本文介绍了如何在go中导入本地包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,开始编写我想要本地化的示例代码.

I am new to go and working on an example code that I want to localize.

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

In the original main.go import statement it was:

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

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

Now I have common and routers package in /home/me/go/src/myapp

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

So I converted the import statement to:

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

但是当我运行 go install myapp 时,我收到以下错误:

But when I run go install myapp I get these errors:

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

此外,当我使用 commonrouters 而不是 ./common./routers 在导入语句,我得到:

Also, when I use common and routers instead of ./common and ./routers in the import statement, I get:

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)

我该如何解决这个问题?

How can I fix this?

推荐答案

好吧,我找到了问题所在.基本上 Go 的导入起始路径是 $HOME/go/src

Well, I figured out the problem. Basically Go starting path for import is $HOME/go/src

所以我只需要在包名前加上myapp,即导入应该是:

So I just needed to add myapp in front of the package names, that is, the import should be:

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

这篇关于如何在go中导入本地包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆