How would you do it in golang: Stacks

How would you do it in golang: Stacks

To implement a stack in golang we can make use of the slice datatype which golang provides which allows us to modify the size on the fly. If we were doing it in C, we would need to define a max size for the array.

Lets start with a simple structure definition and a method to initialize the stack.

type stack struct {
    items []string
    index int
}

// NewStack - function to create a new stack object
func NewStack() *stack {
    return &stack{
        items: []string{},
        index: -1,
    }
}

stack is the struct itself, we define two variables - items which stores the items and index which stores the position of the topmost item. index will store the actual array position (starting with 0)

Now, we create the methods - Push, Pop and Top. To keep things simple, we will only give out an empty string in case there is no item in the stack.

func (s *stack) Push(item string) {
    s.items = append(s.items, item)
    s.index += 1
}

func (s *stack) Pop() string {
    if s.index > -1 {
        item := s.items[s.index]
        s.items = s.items[:len(s.items)-1]
        s.index -= 1
        return item
    }
    return ""

}

func (s *stack) Top() string {
    if s.index > -1 {
        return s.items[s.index]
    }
    return ""
}

Push function is very simple, we take the item and append it at the last and increase the index. In case of Pop function, we first check if the stack is not empty, then we get the last item, however to remove an item from the slice - we need to get all but the last item s.items[:len(s.items)-1], then we decrease the index and return the item. In case of Top we just return top item if its present.

The complete code (with test run) -

package main

import (
    "fmt"
)

type stack struct {
    items []string
    index int
}

func NewStack() *stack {
    return &stack{
        items: []string{},
        index: -1,
    }
}

func (s *stack) Push(item string) {
    s.items = append(s.items, item)
    s.index += 1
}

func (s *stack) Pop() string {
    if s.index > -1 {
        item := s.items[s.index]
        s.items = s.items[:len(s.items)-1]
        s.index -= 1
        return item
    }
    return ""

}

func (s *stack) Top() string {
    if s.index > -1 {
        return s.items[s.index]
    }
    return ""
}

func main() {
    st := NewStack()

    //push hello
    st.Push("h")
    st.Push("e")
    st.Push("l")
    st.Push("l")
    st.Push("o")

    // pop until empty
    for {
        if item := st.Pop(); item != "" {
            fmt.Printf("%s", item)
        } else {
            break
        }
    }
}

This article is part of the "How would you do it in golang?" series and happens to be the first post.