DEV Community

Cover image for Go Struct And Stack Data Structure
Minh-Phuc Tran
Minh-Phuc Tran

Posted on • Updated on • Originally published at phuctm97.com

Go Struct And Stack Data Structure

A byte-sized article that can teach or remind you of a programming concept and/or language in <2 minutes.


Stack

Stack is a LIFO (last-in-first-out) data structure. It's usually used to convert a recursive solution into an iterative solution.

ℹī¸ It is asked a lot during technical interviews at big tech companies.

image.png


Golang implementation

Interestingly enough, there's no built-in implementation of Stack in Go, you'll have to implement it based on a linked list.

import "container/list" // import a package in Golang

type Stack struct { // how a struct is defined
    list *list.List // lowercase var/function is private
}

func (s *Stack) Push(val int) { // upperccase var/function is public
    s.list.PushBack(val)
}

func (s *Stack) Pop() int { // how a struct's function is defined
    item := s.list.Back()
    val := item.Value.(int)
    s.list.Remove(item)
    return val
}

func (s *Stack) Clean() {
    for s.list.Len() > 0 { // there's no 'while' in Golang, only 'for'
        s.list.Remove(s.list.Back())
    }
}
Enter fullscreen mode Exit fullscreen mode

Hope you learned something new from this article 🙏!

If you have any comments, please leave them below. You can always DM and ask me anything on Twitter (@phuctm97) 😉

Top comments (0)