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)?
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
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.
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())
}