du5407
du5407
2014-07-18 05:14

在Golang中导入自定义包

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

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条回答

  • douzhong1730 douzhong1730 7年前

    Read this: http://golang.org/doc/code.html — but in short:

    • One package per directory/one directory per package. You have both server and templates 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 as github.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

    点赞 评论 复制链接分享

为你推荐