2

I'm creating a REST API, and I've separated each resource into it's own package. I've got a User and a Group package. There is a many to many relationship between the two resources. So I need User imported into the Group and Group imported to the User. Since both structs need them as fields.

My question is, should I create another package and import both and then import that package into each of these packages?

Or does it make more sense to combine these two packages into one in go lang?

user1952811
  • 2,398
  • 6
  • 29
  • 49

2 Answers2

5

Put them in the same package, but leave them in separate files.

Joshua
  • 26,234
  • 22
  • 77
  • 106
  • Why do you think this is a better way? – user1952811 Jul 19 '15 at 00:09
  • packages in go are not meant to be super fine grained – Joshua Jul 19 '15 at 00:25
  • 1
    I wrote about cycles a bunch [here](http://stackoverflow.com/questions/20380333/cyclic-dependencies-and-interfaces-in-golang/20394211#20394211), including a user/group example near the end, and an example of a biggish Go package (`net/http`) near the top. In the example there I also tried to say how you could prevent a cycle if the types were in two packages, but really I should edit that to more emphasize that you should maybe stick to one--if you can't conceive of users without groups or groups without users and they're both at the same "layer" of your app, probably want to package together. – twotwotwo Jul 19 '15 at 00:33
0

What I have done in the same situation is:

I put the structures alone into a separate package models, which contains the structures for both as userModel.go and groupModel.go and have kept the functions related to user and group in their own package.

Both user and group packages include the model package.

However, this is a very opinionated answer. As Joshua's post says, we can also put everything together. The deciding factor should be, whether user and group functionalities would be used in other packages outside them or not. If so, then to keep a model package would have its benefits.

Sundar
  • 1,691
  • 1
  • 14
  • 20