I need to use LIFO stack container with push and pop operations, but container
package doesn't have one. Is it supposed to be writen ad-hoc by every programmer, or there is a way to use other data structure as stack (like list in python)?
Asked
Active
Viewed 2,343 times
3

Evgeny Lazin
- 9,193
- 6
- 47
- 83
-
Related: http://stackoverflow.com/questions/2818852/can-anybody-suggest-go-lang-container-for-simple-and-fast-fifo-stack – nemo Jul 02 '13 at 20:20
3 Answers
9
There is no built-in stack type in Go or the standard libraries. However, you can add Push and Pop methods to a slice pretty simply (not unlike the existing methods on lists in python).
type Stack []YourType
func (s *Stack) Push(v YourType) {
*s = append(*s, v)
}
func (s *Stack) Pop() YourType {
ret := (*s)[len(*s)-1]
*s = (*s)[0 : len(*s)-1]
return ret
}
Pretty straightforward
-
-
@nemo I didn't feel there was much more to say, short of an overblown explanation of slice/pointer semantics. – cthom06 Jul 02 '13 at 20:21
-
Hmm, I would've expected something like `yes you have to implement it yourself. For example: ....`. Just posting code gives the intention of not having read the question at all and just throwing code around. But maybe it is just me – nemo Jul 02 '13 at 20:31
-
see my reply,your code is not good,for append is slow and won't release the heap memory after pop,use container/list is better – chuixue Jun 04 '19 at 07:17
3
stack is a subset of list,golang has container/list library,which is simple for implement a stack,here is an example。
//last in first out
stack := list.New()
//stack push use PushBack
for i:=0;i<100;i++ {
stack.PushBack(i)
}
//stack get top use stack.Back()
//stack pop use stack.Remove(stack.Back())
//stack isEmpty use stack.Back() == nil
for stack.Back()!=nil {
fmt.Println(stack.Back().Value)
stack.Remove(stack.Back())
}

chuixue
- 187
- 1
- 4
-
I had no idea about the `container/list` package. I've been implementing push and pop for a long time. Much better to use something like this from the standard library. Thank you! – 17xande Dec 13 '22 at 11:48
-
It's worth mentioning that `container/list` is an implementation of a doubly linked list, and is not typed in the traditional sense. It uses a generic `Element`, which is a struct with `Value` field of type `any`. – 17xande Dec 13 '22 at 12:58
0
There's no container
package in the stdlib. Yet, LIFO is just a stack, it's easily modelled by, for example, a slice. Hence no stdlib LIFO container.

zzzz
- 87,403
- 16
- 175
- 139
-
-
1Yes there is "container" package and under this there is "container/list". – infiniteLearner Jan 02 '22 at 16:26