Please can you help me with getting a struct from main packege called inside another package.
What do you mean by calling a struct? Structure are plain data, you can’t call them…
I mean I want to use the same struct from main package in another package.
If you want to make anything visible outside its package, you have to name it with a capital letter. It’s the way of exporting in go.
I am getting following error: import “api/mm” is a program, not an importable package - import cycle not allowed
You must have two packages importing each other even indirectly.
I’m assuming what you want to do is define a struct inside your
main package, then have other packages you rely on use that struct. This isn’t possible because it always causes an import cycle which is not permitted. That is,
main will always import your other packages that you use, and if any of those packages use the struct defined in
main you will end up with an import cycle that looks like:
main imports X X imports main
If we were to graph this, it would be a cycle not a tree. It may not be that direct, but there WILL be a cycle.
Most people will encourage you to NOT define structs and other functions you need throughout your program in
main and to instead define these in another package to avoid this issue. One technique I’ve seen suggested is something like this:
# put your global structs in this `project` package github.com/you/project/*.go # Put your main package in cmd subdirectory github.com/you/project/cmd/server/main.go # Put your other packages in subdirectories of `project` githubc.om/you/project/pkgA/ githubc.om/you/project/pkgB/ ...
Now when you run your
main.go file it will import whatever packages it needs, and if any of them need to share a struct type across each package you can define it in the
You can read a bit more about this technique in the following articles:
To wrap it all up, I strongly encourage you to not define many data types, functions, etc in your
main package. Instead, define most of them in other packages that
main uses and only have your
main package import and use those packages.
Yes I understood your point. Thanks.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.