Created
September 18, 2016 14:05
-
-
Save Spriithy/12348e059b39189ecb41593f15b48cfb to your computer and use it in GitHub Desktop.
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" | |
func main () { | |
fmt.Println("-= Stack Demo =-") | |
s := Stack() | |
s.Push(Int, 0) | |
s.Push(Int, 1) | |
s.Push(Int, 2) | |
s.Push(Float, 3) | |
s.Push(String, "f") | |
s.Push(Int, 5) | |
fmt.Println(s.String()) | |
fmt.Println("-= End of Demo =-") | |
} | |
type RTType int | |
const ( | |
None RTType = iota | |
Byte | |
Char | |
Int | |
UInt | |
Float | |
String | |
Array | |
) | |
type RTArray struct { | |
size uint64 | |
data []RTObject | |
} | |
type RTObject struct { | |
t RTType | |
val interface{} | |
} | |
type RTStackElement struct { | |
val RTObject | |
next *RTStackElement | |
} | |
type RTStack struct { | |
top *RTStackElement | |
size uint64 | |
} | |
func Stack() (s RTStack) { | |
s = RTStack{ | |
top: nil, | |
size: 0, | |
} | |
return | |
} | |
func (s *RTStack) Len () uint64 { | |
return s.size | |
} | |
func (s *RTStack) Peek () *RTObject { | |
return s.top.val | |
} | |
func (s *RTStack) String () (str string) { | |
str = fmt.Sprintf("Stack [%#v", s.top.val.val) | |
p := s.top.next | |
for p != nil { | |
str = fmt.Sprintf("%s, %#v", str, p.v) | |
p = p.next | |
} | |
str += "]" | |
return | |
} | |
func (s *RTStack) Pop () (v *RTObject) { | |
if s.size > 0 { | |
v, s.top = s.top, s.top.next | |
s.size-- | |
return | |
} | |
return nil | |
} | |
func (s *RTStack) Push (t RTType, o interface{}) { | |
s.top = &RTObject{ | |
v: o, | |
t: t, | |
next: s.top, | |
} | |
s.size++ | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment