我写了一个简单的堆栈实现。这按预期工作。package mainimport "fmt"type Stack struct { data []interface{}}func (s *Stack) isEmpty() bool { return len(s.data) == 0}func (s *Stack) push(item interface{}) { s.data = append(s.data, item) //fmt.Println(s.data, item)}func (s *Stack) pop() interface{} { if len(s.data) == 0 { return nil } index := len(s.data) - 1 res := s.data[index] s.data = s.data[:index] return res}func main() { var stack Stack stack.push("this") stack.push("is") stack.push("sparta!!") for len(stack.data) > 0 { x := stack.pop() fmt.Println(x) }}但是,如果我将三种方法从指针接收器更改为值接收器,如下所示。然后主要不打印任何东西。似乎每次我调用 push 方法时,堆栈都会重新初始化。这是为什么?func (s Stack) isEmpty() bool {func (s Stack) push(item interface{}) {func (s Stack) pop() interface{} {
添加回答
举报
0/150
提交
取消