How to import local files in Go?

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

How to import local files in Go?

问题

我想将我的Go代码组织成更小的块。假设我正在编写一个遵循MVC模式的Web应用程序。我想要这样组织我的代码:

main.go
controllers/whatever/whatever.go
models/whateverelse/whateverelse.go

然后在main.go中,我想要:

import "controllers/whatever"

在Go语言中是否可以实现这样的组织方式?似乎唯一的选择是将文件放在GOPATH/src文件夹中,但这样做并不太合理。在这种情况下,我需要设置git仓库来跟踪$GOPATH/,而不仅仅是跟踪我的项目$GOPATH/src/github/username/project。

英文:

I would like to organize my Go code into smaller chunks. Lets assume I am writing a web application that follows the MVC pattern. I would like to organize my code like this:

main.go
controllers/whatever/whatever.go
models/whateverelse/whateverelse.go

And than in main.go I would like to:

import "controllers/whatever"

Is this possible with Go? It seems the only option, that does not make too much sense is to put the the files into the GOPATH/src folder. In that case I need to set the git repository to track the $GOPATH/ instead of just tracking my project that is $GOPATH/src/github/username/project.

答案1

得分: 3

你提供的解决方案在标准的github目录结构下肯定可行。然而,我想指出的是,要导入一个go库,你只需要从src目录下的目录开始指定该库的路径。

如果你的项目库路径是:

src/yourproject1/controllers

而你的主要代码路径是:

src/yourproject2/main.go

在main.go中,你只需要写:

import "yourproject1/controllers"
英文:

The solution you have could definitely work if you have the standard github directory structure. However, I would like to point out that to import a go library, you just need to specify the path to that library starting from the directory below src.

If your project library has the path:

src/yourproject1/controllers

and your main code has the path:

src/yourproject2/main.go

In main.go, you simply need to say:

import "yourproject1/controllers"

答案2

得分: 1

解决方案来自IRC,感谢jaw22:

import "github.com/yoursuername/yourproject/yourlib"
英文:

The solution came from IRC thanks to jaw22:

import "github.com/yoursuername/yourproject/yourlib"

huangapple
  • 本文由 发表于 2014年4月6日 12:11:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/22889886.html
匿名

发表评论

匿名网友

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

确定