포인터 리시버 vs 값 리시버
Coddy GO 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 107개 중 8번째.
메서드는 value receiver 또는 pointer receiver를 가질 수 있습니다. value receiver는 구조체의 복사본에서 작동합니다. pointer receiver는 원래 구조체에서 작동하며 해당 필드를 수정할 수 있습니다.
값 receiver: copy에서 작동
type Counter struct {
Count int
}
func (c Counter) GetCount() int {
return c.Count
}
// 이것은 원본을 수정하지 않습니다
func (c Counter) IncrementWrong() {
c.Count++ // 복사본만 변경합니다!
}포인터 receiver: original을 수정합니다
// 이것은 원본을 수정합니다
func (c *Counter) Increment() {
c.Count++
}
func (c *Counter) Reset() {
c.Count = 0
}둘 다 함께 사용하기
func main() {
counter := Counter{Count: 0}
counter.Increment()
counter.Increment()
fmt.Println(counter.GetCount()) // 출력: 2
counter.Reset()
fmt.Println(counter.GetCount()) // 출력: 0
}메서드가 데이터만 읽을 때는 값 리시버를 사용하세요. 메서드가 구조체의 필드를 수정해야 할 때는 포인터 리시버(*StructName)를 사용하세요. Go는 참조 처리를 자동으로 수행합니다. 두 경우 모두 같은 방식으로 호출합니다.
챌린지
중급올바른 receiver 유형을 사용하여 Wallet struct에 메서드를 추가하세요:
GetBalance: 값 receiver, 현재 balance를 returnsDeposit: 포인터 receiver, balance에 amount를 더함Withdraw: 포인터 receiver, 충분한 자금이 있을 때만 amount를 뺌
직접 해보기
package main
import "fmt"
func main() {
var balance, deposit, withdraw float64
fmt.Scan(&balance, &deposit, &withdraw)
w := Wallet{Balance: balance}
fmt.Printf("Balance: %.2f\n", w.GetBalance())
w.Deposit(deposit)
fmt.Printf("After deposit: %.2f\n", w.GetBalance())
w.Withdraw(withdraw)
fmt.Printf("After withdrawal: %.2f\n", w.GetBalance())
fmt.Printf("Final balance: %.2f\n", w.GetBalance())
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
1Go OOP 기초
외부 파일Go 워크스페이스와 모듈패키지와 임포트공개 및 비공개 이름Go OOP 입문클래스로서의 구조체구조체 메서드 정의하기포인터 리시버 vs 값 리시버구조체 초기화생성자 함수복습 - 간단한 계산기8에러 처리와 OOP
error 인터페이스사용자 정의 에러 타입에러 래핑 (fmt.Errorf)센티넬 에러errors.Is()와 errors.As()Panic, Defer, Recover요약 - 파일 파서직접 연습해 보세요: 온라인 Go 컴파일러