Go:Receiver
About
메서드를 만들 때 두 가지 방법이 있다.
포인터 리시버
C 처럼 해석해도 된다. Call-By-Pointer 처럼 this 의 "포인터"를 복사한다.
값 리시버
C 처럼 해석해도 된다. Call-By-Value 처럼 this 의 "값"을 복사한다.
Example
package main
import "fmt"
type Person struct {
Name string
Age int
}
// Pointer receiver - 원본 수정 가능
func (p * Person) SetAge(age int) {
p.Age = age
}
// Value receiver - 원본 수정 불가
func (p Person) SetAge(age int) {
p.Age = age
}
// Value receiver - 원본 수정 불가
// Works on a copy, doesn't modify original
func (p Person) GetAge() int {
return p.Age
}
func main() {
person := Person{Name: "Alice", Age: 20}
person.SetAge(25) // 원본이 25로 변경됨 (Changes original to 25)
fmt.Println(person.Age) // 출력: 25
// 만약 SetAge가 값 리시버였다면?
// If SetAge was a value receiver:
// person.Age는 여전히 20 (would still be 20)
}