Code generation with go

When it comes to using any statically typed language, the basic code generation capabilities are today’s standards. Just to name some, Java, C++ or Rust all have generics build in. Ewen I thought that Golang is no exception in this rule, when i first started working with it. Well, if you already have some experience with go, you probably already know its cons. Horrible error handling and no generics, and that’s about it because go is otherwise absolutely amazing.

Lack of generics can be most noticeable when working with slices. There are some simple actions you have to do when working with them, and ewe though they are simple, it really starts to be annoying if you have to repeat yourself hundred times around your project.

Why does Golang have none? Well from what a hurt, lot of people are actively complaining, and go dev team is actively hesitating. Why are they so hesitant, although they already have working prototype? From what I understand, generics are slow, and our insanely fast go compiler would would not be so insanely fast anymore.

Alternatives

Now, let ‘s not just talk about problems but also introduce some solutions, shell we. When I was working on my game I runed in to obstacle. When constructing ECS I found out that I have to use interface{} of write logic for entity storage 10 times. As am too lazy to do such thing nor a wanted to trade performance for using interface{},I started to play with an idea of code generation. Computer is more repayable than any human after all.

So, I created gogen. It wasn’t even that hard and I solved go problem with go, how lovely. With just a few comments, I can now turn any code to template. One more comment and command, and I have code generated. If I make a change to a template I just have to run command again and code is updated.

Conclusion

Maybe one day the generic pull request will make its way to a main branch, but until then, you can consider gogen as a great alternative. Of course, I have to mention that go compiler can generate some code for you, but you have to write a little article to your command line anytime you want to accomplish that. With gogen you can make annotations, just once, and generate all your templates from anywhere with just one word. Here is the repository.