DEV Community

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

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

4 1

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) 😉

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay