Created
July 16, 2013 13:57
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wouldn't it be better / more elegant to use method notation?