This is a creation in Article, where the information may have evolved or changed.
The container in the go language are heap, list, ring, and no stack.
Where heap is the priority queue, although there is a push ()/pop () interface, use the heap to implement the heap. Interface interface, not concise.
So here's a simple stack with a list that's left for him to use.
Package StackImport"container/list"Type Stackstruct {List *list. List }Func newstack () *Stack {List: =list. New () return&Stack{list} }Func (Stack *stack) Push (valueInterface{}) { Stack.list.PushBack (value) }Func (Stack *stack) Pop ()Interface{} {E: =Stack.list.Back () ifE! =Nil { Stack.list.Remove (e) returnE.value } returnNil }Func (Stack *stack) Peak ()Interface{} {E: =Stack.list.Back () ifE! =Nil { returnE.value } returnNil }Func (Stack *stack) Len ()int { returnStack.list.Len () }Func (Stack *stack) Empty ()BOOL { returnStack.list.Len () = =0}
Test code:
Package StackImport"Testing"Func Teststack (T *testing. T) {Stack: =Newstack ()Stack. Push (1)Stack. Push (2)Stack. Push (3)Stack. Push (4)Len: =stack. Len () ifLen! =4 {T.errorf ("stack. Len () failed. Got%d, expected 4.", Len) }Value: = Stack. Peak (). (int) ifValue! =4 {T.errorf ("stack. Peak () failed. Got%d, expected 4.", value) }Value = Stack. Pop (). (int) ifValue! =4 {T.errorf ("stack. Pop () failed. Got%d, expected 4.", value) }Len =stack. Len () ifLen! =3 {T.errorf ("stack. Len () failed. Got%d, expected 3.", Len) }Value = Stack. Peak (). (int) ifValue! =3 {T.errorf ("stack. Peak () failed. Got%d, expected 3.", value) }Value = Stack. Pop (). (int) ifValue! =3 {T.errorf ("stack. Pop () failed. Got%d, expected 3.", value) }Value = Stack. Pop (). (int) ifValue! =2 {T.errorf ("stack. Pop () failed. Got%d, expected 2.", value) }Empty: =stack. Empty () ifEmpty {T.errorf ("stack. Empty () failed. Got%d, expected false.", empty) }Value = Stack. Pop (). (int) ifValue! =1 {T.errorf ("stack. Pop () failed. Got%d, expected 1.", value) }Empty =stack. Empty () if!Empty {T.errorf ("stack. Empty () failed. Got%d, expected true.", empty) }Nilvalue: =stack. Peak () ifNilvalue! =Nil {T.errorf ("stack. Peak () failed. Got%d, expected nil.", Nilvalue) }Nilvalue =stack. Pop () ifNilvalue! =Nil {T.errorf ("stack. Pop () failed. Got%d, expected nil.", Nilvalue) }Len =stack. Len () ifLen! =0 {T.errorf ("stack. Len () failed. Got%d, expected 0.", Len) }}
Download Stack.zip