값별 수신자 대 포인터 혼동 별 수신자 [중복]

Dec 28 2020

간단한 스택 구현을 작성했습니다. 이것은 예상대로 작동합니다.

package main

import "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{} {

답변

1 LunaLovegood Dec 28 2020 at 11:15

In value receiver Go는 변수의 복사본을 만들고 복사본을 변경합니다. 참조 수신기에서만 실제 stack변수가 업데이트됩니다.

상세 사항은, https://tour.golang.org/methods/4