在子包中引用主包(package main)。

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

Referencing package main in a subpackage

问题

你好!根据你的描述,你想在子包(routes包)中引用位于主包(main包)中的日志记录器(Logger)。如果Logger是公开的,它应该已经可以在routes包中使用。但是,你在routes.go中却收到了"undefined: Logger"的错误。

这个问题可能是由于循环导入引起的。routes.go导入了main包,而main.go又导入了routes包,导致了循环导入的错误。

为了解决这个问题,你可以将logger.go文件移动到一个独立的包中,例如common包。然后,你可以在main包和routes包中都导入common包,并使用其中定义的Logger。

你的新目录结构可能如下所示:

  • main.go
  • common/logger.go
  • routes/routes.go
  • ...

在main.go和routes.go中,你可以使用以下导入语句来引用common包:

import "your-module-path/common"

然后,你就可以在routes.go中使用common包中定义的Logger了。

希望这可以帮助到你!如果还有其他问题,请随时提问。

英文:

new to Golang and have a seemingly simple question. If I have a logger in package main (and defined in logger.go) at my project root, how do I reference that logger in a subpackage (ie: my routes package)?

My directory structure is:

  • main.go
  • logger.go
  • routes\routes.go
  • ...

I would think if Logger is public it would already be available to routes, but I get 'undefined: Logger' in routes.go. And if I try to import my main package in routes.go I get an 'import cycle not allowed' error since routes.go imports package main and main.go imports package routes.

Any help would be much appreciated!

答案1

得分: 0

解决这个问题的唯一方法是将共享的日志记录器移动到一个第三方包中,并将其导入到mainroutes中。否则,你会遇到循环依赖的问题,正如你所见,这是不允许的。

只需添加一个名为logger的文件夹,并将你的日志记录器放在其中。现在将其导入到其他两个包中,问题就解决了。

英文:

The only way to resolve this is to move the shared logger to a third package and import it into both main and routes. Otherwise you get a cyclic dependency which as you've seen is not allowed.

Simply add a folder called logger and put your logger in there. now import it into the other 2 packages, and you're done.

huangapple
  • 本文由 发表于 2015年2月7日 05:23:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/28375034.html
匿名

发表评论

匿名网友

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

确定