Skip to content

Instantly share code, notes, and snippets.

@trajber
Last active December 23, 2015 02:09
Show Gist options
  • Save trajber/6565081 to your computer and use it in GitHub Desktop.
Save trajber/6565081 to your computer and use it in GitHub Desktop.
A simple implementation of a stack in Golang.
package main
import (
"fmt"
)
type Stack struct {
elements []interface{}
}
func NewStack() *Stack {
s := new(Stack)
s.elements = make([]interface{}, 0)
return s
}
func (s *Stack) Push(e interface{}) *Stack {
s.elements = append(s.elements, e)
return s
}
func (s *Stack) Pop() (e interface{}) {
e, s.elements = s.elements[len(s.elements)-1], s.elements[:len(s.elements)-1]
return
}
func (s *Stack) Size() int {
return len(s.elements)
}
func main() {
s := NewStack()
s.Push(1).Push(2).Push(3).Push("Hello")
for s.Size() > 0 {
fmt.Println(s.Pop())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment