1

I have this package structure in my go module, and I am adding commands using cobra-cli:

.
├── LICENSE
├── cmd
│   ├── constants.go
│   ├── root.go
│   └── tools
│       └── tools.go
├── go.mod
├── go.sum
└── main.go

In tools.go, I want to import constants.go which I want to define for globally used constants across all files in my module, and is simple go file:

package cmd

const (
    FOO = "https://a.b.c"
    BAR = "https://p.q.r"
)

How do I import this? Also is there a better way of doing this?

Ufder
  • 527
  • 4
  • 20
  • Import the package containing constants.go as "modulename/cmd" where *modulename* is replaced with the name of the module in go.mod. Reference the constants as cmd.FOO and cmd.BAR. – Charlie Tumahai Sep 17 '22 at 19:17
  • I had tried that, it gives me the error `import cycle not allowed` – Ufder Sep 17 '22 at 19:36
  • 2
    Probably `tools` imports `cmd` and vice versa. That is not allowed and it is often a mark of bad design, which is true in this case: global place for constants is the evil idea, keep constants where they are used – slsy Sep 17 '22 at 19:38
  • You are right, that was the case. There are some constants which will be heavily used across all commands that I am adding, meaning they are truly global. What is a good way to structure this? I don't want to define these in multiple places. – Ufder Sep 17 '22 at 19:41
  • 1
    Break the cycle by moving the constants to a new package. – Charlie Tumahai Sep 17 '22 at 20:15
  • `I had tried that, it gives me the error import cycle not allowed` because `constants.go ` and `tools ` is the same package , When your import, you import all of into `cmd` package – taismile Sep 18 '22 at 04:20

1 Answers1

0

import cycle not allowed when you used constant.go inside tools.go and used tools.go inside constant.go, and create a cycle call each other, please check you code import cycle not allowed when you used constant.go inside tools.go and used tools.go inside constant.go, and create a cycle call each other, please check you code

taismile
  • 101
  • 7