Skip to content

Instantly share code, notes, and snippets.

@sam-falvo
Created July 16, 2013 13:57
Show Gist options
  • Save sam-falvo/6008929 to your computer and use it in GitHub Desktop.
Save sam-falvo/6008929 to your computer and use it in GitHub Desktop.
generic data structure and type-specific specialization in Go (example; not the only way to do it, but closest to what Java does).
package main
import "fmt"
// ====== Generic Stack implementation
package genericStack
type GenericStack struct {
space []interface{}
top int
}
func Reset(gs *GenericStack, size int) {
gs.space = make([]interface{}, size)
gs.top = 0
}
func Push(gs *GenericStack, obj interface{}) error {
if gs.top < len(gs.space) {
i := gs.top
gs.top++
gs.space[i] = obj
return nil
}
return fmt.Error("Attempt to push into full stack")
}
func Pop(gs *GenericStack) (interface{}, error) {
if gs.top > 0 {
gs.top--
return gs.space[i], nil
}
return fmt.Error("Attempt to pop an empty stack")
}
// ====== A "String" stack
package stringStack
import "genericStack"
type StringStack genericStack.GenericStack
func Reset(ss *StringStack, size int) {
genericStack.Reset(genericStack.GenericStack(ss), size)
}
// No need for type-assertions because the compiler will object
// to code that attempts to push non-string types onto a StringStack.
func Push(ss *StringStack, st string) error {
return genericStack.Push(genericStack.GenericStack(ss), st)
}
func Pop(ss *StringStack) (string, error) {
obj, err := genericStack.Pop(genericStack.GenericStack(ss))
if err != nil {
return "", error
}
st, ok := obj.(string)
if !ok {
return "", fmt.Error("String stack returned something that wasn't a string.")
}
return st, nil
}
@cassava
Copy link

cassava commented Jul 16, 2013

Wouldn't it be better / more elegant to use method notation?

func (gs *GenericStack) Pop() (interface{}, error)
func (ss *StringStack) Pop() (string, error)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment