2,190
社区成员
发帖
与我相关
我的任务
分享
const stackLenth = 4
type Stack []string
func (self Stack) Size() (lenth int) {
lenth = len(self)
return
}
func (self Stack) String() (stackInfo string) {
for key, value := range self {
stackInfo += "[" + strconv.Itoa(key) + ":" + value + "]"
}
return
}
func (self Stack) Push(s string) {
self = append(self, s)
}
func (self Stack) Pop() {
lastKey := self.Size()
if (lastKey > 0) {
self = self[:lastKey]
}
}
func main() {
var stack = make(Stack, 0, stackLenth)
stack.Push("a")
fmt.Println(stack)
stack.Push("b")
fmt.Println(stack)
stack.Pop()
fmt.Println(stack)
}
package main
import (
"strconv"
"fmt"
)
const stackLenth = 4
type Stack []string
func (self *Stack) Size() (lenth int) {
lenth = len(*self)
return
}
func (self Stack) String() (stackInfo string) {
for key, value := range self {
stackInfo += "[" + strconv.Itoa(key) + ":" + value + "]"
}
return
}
func (self *Stack) Push(s string) {
*self = append(*self, s)
}
func (self *Stack) Pop() string {
lastKey := self.Size()
if (lastKey > 0) {
r := (*self)[lastKey-1]
*self = (*self)[:lastKey-1]
return r
}
return ""
}
func main() {
var stack = make(Stack, 0, stackLenth)
stack.Push("a")
fmt.Println(stack)
stack.Push("b")
fmt.Println(stack)
fmt.Println(stack.Pop())
fmt.Println(stack)
}
另外,上面的代码中,只有Stack对象实现了Stringer接口,而 *Stack是没实现Stringer的,你仔细体会一下。