A stack is an ordered data structure that follows the Last-In-First-Out (LIFO) principle. Stacks are most easily implemented in Golang using slices:
append
function.An implementation of a stack is shown below:
package mainimport "fmt"type Stack []string// IsEmpty: check if stack is emptyfunc (s *Stack) IsEmpty() bool {return len(*s) == 0}// Push a new value onto the stackfunc (s *Stack) Push(str string) {*s = append(*s, str) // Simply append the new value to the end of the stack}// Remove and return top element of stack. Return false if stack is empty.func (s *Stack) Pop() (string, bool) {if s.IsEmpty() {return "", false} else {index := len(*s) - 1 // Get the index of the top most element.element := (*s)[index] // Index into the slice and obtain the element.*s = (*s)[:index] // Remove it from the stack by slicing it off.return element, true}}func main() {var stack Stack // create a stack variable of type Stackstack.Push("this")stack.Push("is")stack.Push("sparta!!")for len(stack) > 0 {x, y := stack.Pop()if y == true {fmt.Println(x)}}}
type
is made for a list called Stack
. This allows us to create methods on Stack
, just like the methods of a class.Push
and Pop
methods are implemented on lines and , respectively. The Pop
method utilizes the IsEmpty
helper function to cater to the exception that occurs when the stack is empty.main
function, the stack is populated with three strings. The values stacked in the stack are then popped, notice the order in which they are printed. The output confirms that the stack correctly follows the LIFO principle.Note that the stack is initialized to contain strings. Changing the type to
interface{}
would allow the stack to work for any data type.
Free Resources