【小白问题】关于用切片实现堆栈的一些问题

jrient jrient 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
在执行push方法中处理切片内容,却没有改变外界的数值。
首先,我认为切片作为指针类的数据,传递调用后的值变化会作用到到本身啊。
其次,我对切片定义别名的操作还没有理解太透彻,希望哪位可以点醒下。
请不要聊这里应该使用结构体的问题谢谢。

代码如下:
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)


}
...全文
评论 4
收藏 已收藏
分享
返回顶部
jrient
go语言 2,351 成员 924 内容