英文:
Importing custom packages in golang
问题
我有以下文件:
app/main.go
app/server/server.go
app/server/templates.go
main.go
中有一个 import "app/server"
的导入语句,但是在编译时,它报错:
在 app/server 中找到了 server (server.go) 和 templates (templates.go) 两个包
我猜测它对要加载的包感到困惑了?我的意图是 server.go
将设置路由并导入 ./templates.go
来渲染模板。
有没有更好的文件布局方式?我应该将 templates.go
移动到它自己的目录中吗?
英文:
I have the following:
app/main.go
app/server/server.go
app/server/templates.go
main.go
has an import statement of import "app/server"
, but when compiled, it complains about:
found packages server (server.go) and templates (templates.go) in app/server
Im guessing it is confused about which package to load up? My intention is that server.go
will setup the routes and import ./templates.go
to render templates.
Is there a better way to layout files? Should I move templates.go
to it's own directory?
答案1
得分: 4
阅读这个链接:http://golang.org/doc/code.html — 但简而言之:
-
每个目录一个包/每个包一个目录。你有
server
和templates
两个包,你应该只有一个package main
,如果你尝试编译一个可执行文件而不是一个库。 -
不要使用"相对"导入。使用完全限定的路径 - 例如,如果你的基本项目是
$GOPATH/src/github.com/JohnFromSO/myapp
,那么你应该将子包导入为github.com/JohnFromSo/myapp/database
。 -
你可能不需要将
templates.go
拆分为一个单独的包 - 一个好的经验法则是"如果这个包独立存在,或者可以被其他人使用,那么它是否可用?"
另一个好的阅读材料是https://medium.com/@benbjohnson/structuring-applications-in-go-3b04be4ff091
英文:
Read this: http://golang.org/doc/code.html — but in short:
-
One package per directory/one directory per package. You have both
server
andtemplates
packages where you should just have one -package main
if you are attempting to compile a binary and not a library. -
Don't use "relative" imports. Use the fully qualified path - i.e. if your base project is
$GOPATH/src/github.com/JohnFromSO/myapp
then you would import sub-packages asgithub.com/JohnFromSo/myapp/database
. -
You probably don't need to split out
templates.go
into a separate package - a good rule of thumb is "would this package be usable if it stood on its own/usable by others?"
Another good read is https://medium.com/@benbjohnson/structuring-applications-in-go-3b04be4ff091
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论