Stack In Golang

Implementation of stack data structure

Bits
2 min readNov 13, 2022

Definition

Stack: Stack is a linear type of data structure that follows the LIFO (Last-In-First-Out) principle and allows insertion and deletion operations from top of the stack.
Top: It represents the recent most element inserted in the stack.

Methods

  1. Push: This method is responsible to insert an element at the top of the stack.
  2. Pop: This method is responsible for deleting the top element of the stack.
  3. Top: This method gives the topmost element of the stack if available otherwise returns nil.
  4. GetStack: Gives the stack back to the function call.
  5. IsEmpty: Returns true if the stack is empty else returns false.
package datastructures

import (
"fmt"
"reflect"
)

type StackServicer interface {
Push(ele any)
Pop()
Top() any
GetStack() []any
IsEmpty() bool
}

type stack struct {
stackArr []any
stackType reflect.Type
}

func InitStack[T string | []int](ele T) StackServicer {
var stackArr []any
var stackType reflect.Type
if arr, ok := any(ele).([]int); ok {
for i := 0; i < len(ele); i++ {
stackArr = append(stackArr, arr[i])
}
stackType = reflect.TypeOf(len(arr))
} else if arr, ok := any(ele).(string); ok {
for i := 0; i < len(ele); i++ {
stackArr = append(stackArr, arr[i])
}
stackType = reflect.TypeOf(ele)
}

return &stack{
stackArr: stackArr,
stackType: stackType,
}
}

func (s *stack) Push(ele any) {
if s.stackType == reflect.TypeOf(ele) {
s.stackArr = append(s.stackArr, ele)
} else {
fmt.Println("Does not support this type")
}
}

func (s *stack) Pop() {
s.stackArr = s.stackArr[0 : len(s.stackArr)-1]
}

func (s *stack) Top() any {
if len(s.stackArr) == 0 {
return nil
} else {
return s.stackArr[len(s.stackArr)-1]
}
}

func (s *stack) GetStack() []any {
return s.stackArr
}

func (s *stack) IsEmpty() bool {
return len(s.stackArr) == 0
}

I hope this article helps to understand the stack in golang. Please comment below in case of any errors or further suggestions. Thanks!

--

--