Search code examples
goproject-managementpackagedirectory-structure

Go: how many packages per project


While working on my Go project today, I realised I had ran into a small problem. I had a package that had a struct that held a pointer to a struct from another package. However, that package also made use of a struct from the other package. In C and C++, this wouldn't pose an issue, as I'd use a header guard. However, in Go, such a program won't compile due to infinite import recursion.

This made me wonder, are there too many packages in my project? Should I favour bigger packages? I've always been told that each package should be specifically focused on one thing.

Right now, my structure is like this.

game/                  <-- imports engine, needs to access the resource manager a lot
    video/             <-- rendering goes here
        renderer.go
        shader.go
        scene.go
        ...
    engine/            <-- imports video, file, etc
        root.go        <-- contains a Root struct, handles initialisation etc
        resource.go
        ...
    file/
        dds.go
        config.go
        resource_list.go
        script.go
        ...
    main.go
    ...

That said, here are my questions:

  • How would you solve this? Would you combine the video and engine packages? Redesign your program so that video no longer depends on engine?
  • How do you decide when it's appropriate to make a new package? Do you base it on functionality? Do you group it by category?
  • How much use do you make of the main package? I personally tend to get out of it as quickly as possible, maybe because I'm too used to OOP.

Solution

  • As these questions are rather broad and project-specific, I can only hope this is of any help:

    • Personally, I would try to create a third package on which both video and engine can rely. Depending on the project though, this might be a difficult thing to do, and they might need to be merged.
    • A new package is usually about one specific task. Depending on the project, this might be database I/O, including all models as well - but it might also be a package that's just about reading configuration files from the disk.
    • As I've built mostly web-apps, I use the main package to get things started: listening to ports, calling other functions, making sure database connections are closed properly, etc.

    Example (not sure if helpful? ) :

    I once had a package that was just about configurations (config), which referred to the rest of the packages (for some reason). The other packages however, depended on those configurations inside config. This is where the main package can come in handy: linking the config package with the other packages, by means of parameters.


    The comment from VonC is also very useful and elaborate. It will probably help you more than this.