dongyu3659 2016-05-18 22:15
浏览 378
已采纳

GoLang和带有相对路径的软件包布局

I'm learning Go language and I've made this example: http://thenewstack.io/make-a-restful-json-api-go/ to build a simple REST API.

I've compiled it and all works fine but all sources are in the main package.

Now I want to organize my .go files in packages, so I move them into some folders this way:

GOPATH\bin
GOPATH\pkg
GOPATH\src\pack1\Handlers.go
GOPATH\src\pack1\Logger.go
GOPATH\src\pack1epo.go
GOPATH\src\pack1\Todo.go
GOPATH\srcouter\Router.go
GOPATH\srcouter\Routes.go
GOPATH\src\Main.go

Main.go uses all the router package so I've put in the import section: "./router". Router.go uses the pack1 package, so in Router.go I've imported "../pack1". Now if I try to "go build Main.go" I get:

router\Router.go:6: imported and not used: "_/D_/GOPATH/src/pack1"
router\Router.go:14: undefined: Logger

and similar errors, so seems that the import of pack1 package that I've made, it's wrong. Of course in all files belonging to pack1, in the header I've put the "package pack1" definition.

I've also read that the relative imports are not suggested in Go and it could be useful to use the remote packages such ad importing "github.com/myrepo/mypackage". But I dont want to use remote imports; I want to push all my files in a second moment.

Could you help me to better understand what is the way to have local imports between packages in Go language?

thanks in advance

  • 写回答

2条回答 默认 最新

  • dongzhong5967 2016-05-19 00:26
    关注

    The reason you're not supposed to use relative imports is that they don't work inside of $GOPATH. Get rid of the "relative" part of your import paths, since all imports are relative to $GOPATH/src

    import (
        "pack1"
        "router"
    )
    

    You will also want to move your Main.go into a package as well, so you you can make full use of the go tools.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?