One of the things that caught my eye when I was experimenting with the Go language was the append() function.

Example usage:

The append() function adds an element into a slice, and if the backing array of the slice is not large enough, it will be reallocated with a bigger size. This works exactly like std::vector::push_back() in C++.

What I generally like about the Go’s approach to the dynamic array is that it is minimalistic. You have one function and that’s it.

The minimalism is one of the top reasons that made C language so popular and successful, especially in the world of embedded systems. Unfortunately this minimalism, which makes C easy to port to almost any platform comes with a cost of having zero data structures built into the language or the standard library.

One of the most useful data structures is definitely the dynamic array and there are many libraries out there providing its implementation, but in my personal projects I prefer to quickly port Go’s append() function to C.

Append in C

The C’s version of append() is not as neat as in Go because we have to explicitly pass the capacity and the length, but the implementation consists of just a few lines of code.

Usage