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

jrient 2018-05-05 10:51:02
在执行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)


}
...全文
791 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Darlzan 2018-06-20
  • 打赏
  • 举报
回复
楼上已提到相关原因,方法的接收器可以是对象也可以是对象的指针,使用一个对象作为接收机那就会涉及值拷贝。你想要修改对象内的值,那就只能用指针对象作为接收器。(指针对象作为接收器定义的方法,直接用对象也能调,go会自动处理)。 基于这个原因,你的代码可以修改如下:

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的,你仔细体会一下。
李睿_Lee 2018-05-11
  • 打赏
  • 举报
回复
先不管pop和push能不能作用在同个stack里。你这个pop函数就已经有问题。根本没有pop成功,长度还是原来的,你还得好好看看slice这个知识点。另外,一般pop还要有返回值,返回一个item的。
maquan 2018-05-07
  • 打赏
  • 举报
回复
Go 只有“值传递”,没有“引用传递”。 当一个 slice 作为参数时,传递的是这个 slice 的“值”。你肯定知道,一个 slice 的值是由三个字段组成的,一个地址(address)、一个长度(length)、一个容量(capacity)。当作为入口参数时,slice 变量的这三个字段被复制并传入,在函数内部的修改会影响到底层数组(underlying array),也会影响复制后的 slice 值,但不会影响实参 slice 的值。比如你的代码,调用 Push 之后,stack 的底层数组其实已经变化了,但因为 stack 的 len() 并没有变,所以你没观察到而已。

2,190

社区成员

发帖
与我相关
我的任务
社区描述
go语言学习与交流版
社区管理员
  • go语言社区
  • Freeman Z
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧