Stack Using Golang Generics
With the recent introduction of generics in Golang, they have proved themselves not only elegant and simple, but also very efficient, check out the performance characteristics here. Now it is time to demonstrate their power in creating flexible data structures in this post. As promised in a later post, we are going to implement a stack in this post. The rest of this post is organized as follows:
- what is a stack
- stack methods
- implementation in Golang
- testing our stack
What is a Stack
Stacks are simple data structures that powers a great deal of modern computational systems like function calls in compilers themselves, LRU policy of memory block replacements, bracket matching problems and many many more. Stacks were first introduced in 1964 by Alan M. Turing and they were gaining popularity ever since.
Stack Methods
- Init
- Pop
- Push
- Peak
The "Init" method usually used to instantiate the stack i.e allocate memory to be used in the stack. In strongly typed languages like Golang, it is required to define the type of elements that goes into the stack. In addition to the memory allocations, it is required for the stack to be thread safe, if it is going to run in a multi-threading environment.
Stack Implementation in Golang
Here goes the interesting stuff. First we create a struct that will represent our stack. This struct will contain a slice that will represent our data, a locking mechanism for safe threading. It's required to keep these struct members private so no one miss with them from outside our package. These Items will be manipulated by our receiver functions only. So our struct will look something like this:
So in order to instantiate this struct and use it, we might provide a method to do that. This method will return a pointer to a stack so the caller can invoke the struct methods on them. The Other Three methods required by a stack to function probably are displayed below. Notice here that we do not allow simulations reads/writes to our data structure.
Comments
Post a Comment