开发Golang包时,无法使用相对路径。

huangapple go评论91阅读模式
英文:

Developing Golang Package, cannot use relative path

问题

我正在尝试开发一个简单的Go语言包,假设它的名字是"Hello",目录结构如下:

hello
   games
   game-utils

然后在hello.go(主要代码文件)中,我有以下代码:

import (
    gameUtils "./game-utils"
    "./games"
)

这在本地工作得很好,但是当我将代码推送到远程仓库(例如github.com)并尝试使用go get安装时,问题就出现了。问题出在导入路径上,我必须将其更改为:

import (
    gameUtils "github.com/user/hello/game-utils"
    "github.com/user/hello/games"
)

问题是,每次我开发这个包时,我都不能使用"github.com/user/hello/game-utils"这样的导入路径,因为显然我还没有将其推送到远程仓库,我需要使用"./game-utils"来导入。

有没有一种优雅的方法来解决这个问题?

英文:

I'm trying to develop a simple golang package

let's say its name is "Hello", the directory structure is like below

hello
   games
   game-utils

then in hello.go (the main code) I have these:

import (
    gameUtils "./game-utils"
    "./games"
)

ok this worked well until I push to remote repo(e.g github.com) and try to use go get to install it. The problem was with the import path, I must change it to

import (
    gameUtils "github.com/user/hello/game-utils"
    "github.com/user/hello/games"
)

the question is, everytime I develop the package I cannot import using "github.com/user/hello/game-utils" because obviously I wouldn't have pushed it to the remote repo, I need to import it using "./game-utils".

Is there any elegant way to fix this issue?

答案1

得分: 4

阅读这个

你应该始终使用以下方式导入它:

import "github.com/user/hello/game-utils"

这是因为go工具的工作方式。它会在本地机器上的目录"GOPATH/src/github.com/user/hello/game-utils"中查找它。正如@JimB指出的那样,编译器总是使用本地源代码,并且导入路径是相对于GOPATH/src的。

go get工具是唯一一个在互联网上查找源代码的工具。获取源代码后,它会将其下载到"GOPATH/src/IMPORT_PATH",这样编译器和其他工具就可以在本地结构中看到它们了。

如果你正在创建一个新项目,你应该遵守相同的目录结构。如果你计划将代码上传到github,那么在"GOPATH/src/github.com/YOUR-GITHUB-USER/PROYECT-NAME"中手动创建文件夹,然后在其中初始化你的git仓库。(这至少适用于githgsvn以及githubbitbucketgoogle code)。

英文:

Read this.

You should always import it using:

import "github.com/user/hello/game-utils"

This is because of how the go tool works. It will look for it on the local machine in the directory: "GOPATH/src/github.com/user/hello/game-utils". As @JimB points out, the compiler always works with the local sources and the import paths are relative to GOPATH/src.

The go get tool is the only one that looks for the sources on the internet. After getting them, it downloads them to "GOPATH/src/IMPORT_PATH" so the compiler and the other tools can now see them in their local structure.

If you are creating a new project you should respect the same directory structure. If you are planning to upload your code to github then create manually the folder "GOPATH/src/github.com/YOUR-GITHUB-USER/PROYECT-NAME" and then initialize your git repo in there. (This works at least on git, hg, svn and github, bitbucket and google code)

huangapple
  • 本文由 发表于 2014年12月20日 03:22:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/27572601.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定