Looking for reasonable stack implementation in golang?

It's a matter of style and personal taste, your code is fine (apart from not being thread safe and panicking if you pop from an empty stack). To simplify it a bit you can work with value methods and return the stack itself, it's slightly more elegant to some tastes. i.e.

type stack []int

func (s stack) Push(v int) stack {
    return append(s, v)
}

func (s stack) Pop() (stack, int) {
    // FIXME: What do we do if the stack is empty, though?

    l := len(s)
    return  s[:l-1], s[l-1]
}


func main(){
    s := make(stack,0)
    s = s.Push(1)
    s = s.Push(2)
    s = s.Push(3)

    s, p := s.Pop()
    fmt.Println(p)

}

Another approach is to wrap it in a struct, so you can also easily add a mutex to avoid race conditions, etc. something like:

type stack struct {
     lock sync.Mutex // you don't have to do this if you don't want thread safety
     s []int
}

func NewStack() *stack {
    return &stack {sync.Mutex{}, make([]int,0), }
}

func (s *stack) Push(v int) {
    s.lock.Lock()
    defer s.lock.Unlock()

    s.s = append(s.s, v)
}

func (s *stack) Pop() (int, error) {
    s.lock.Lock()
    defer s.lock.Unlock()


    l := len(s.s)
    if l == 0 {
        return 0, errors.New("Empty Stack")
    }

    res := s.s[l-1]
    s.s = s.s[:l-1]
    return res, nil
}


func main(){
    s := NewStack()
    s.Push(1)
    s.Push(2)
    s.Push(3)
    fmt.Println(s.Pop())
    fmt.Println(s.Pop())
    fmt.Println(s.Pop())
}

I believe it would be nice if we could take advantage of Go's standard libs instead of creating self-defined data structure like @guy_fawkes did. Although he did a great job, it's not a standard way to use singly linked list.

To get list's tail in O(1) time complexity, I would use doubly linked list. I trade space for time.

I also take @Not_a_Golfer's advice to add a lock to the stack.

import (
    "container/list"
    "sync"
)

type Stack struct {
    dll   *list.List
    mutex sync.Mutex
}

func NewStack() *Stack {
    return &Stack{dll: list.New()}
}

func (s *Stack) Push(x interface{}) {
    s.mutex.Lock()
    defer s.mutex.Unlock()

    s.dll.PushBack(x)
}

func (s *Stack) Pop() interface{} {
    s.mutex.Lock()
    defer s.mutex.Unlock()

    if s.dll.Len() == 0 {
        return nil
    }
    tail := s.dll.Back()
    val := tail.Value
    s.dll.Remove(tail)
    return val
}

Click this playground to preview the result.


Here is a LIFO implementation using linked data structure

package stack

import "sync"

type element struct {
    data interface{}
    next *element
}

type stack struct {
    lock *sync.Mutex
    head *element
    Size int
}

func (stk *stack) Push(data interface{}) {
    stk.lock.Lock()

    element := new(element)
    element.data = data
    temp := stk.head
    element.next = temp
    stk.head = element
    stk.Size++

    stk.lock.Unlock()
}

func (stk *stack) Pop() interface{} {
    if stk.head == nil {
        return nil
    }
    stk.lock.Lock()
    r := stk.head.data
    stk.head = stk.head.next
    stk.Size--

    stk.lock.Unlock()

    return r
}

func New() *stack {
    stk := new(stack)
    stk.lock = &sync.Mutex{}

    return stk
}

Tags:

Go