Go lang - 12 : 메서드

개발조아·2022년 3월 26일
0

go-lang

목록 보기
12/13

메서드 형태

func에 추가적으로 리시버를 명시해준다
아래 func 뒤에 (d Duck) 부분이 리시버이다.

여기서 리시버를 포인터로 받거나 값을 받는 경우가 있다

포인터를 받으면 리시버가 가진 값이 변경될 수 있고
아니라면 값으로 받으면 된다.

값 리시버

package main

import "fmt"

type Duck struct {
	Name  string
	Age   int
	Sound string
}

func (d Duck) String() string {	// 메서드
	return fmt.Sprintf("%s, age %d, sound is %s ", d.Name, d.Age, d.Sound)
}

func main() {
	d := Duck{
		"오리",
		13,
		"꽥꽥",
	}
	fmt.Println(d.String())
}

Console

포인터 리시버

package main

import "fmt"

type Duck struct {
	Name  string
	Age   int
	Sound string
}

func (d Duck) String() string {
	return fmt.Sprintf("%s, age %d, sound is %s ", d.Name, d.Age, d.Sound)
}

func (d *Duck) AddYear(i int) {	// 포인터 리시버
	d.Age = d.Age + i
}

func main() {
	d := Duck{
		"오리",
		13,
		"꽥꽥",
	}
	d.AddYear(5)	// Age에 5를 더한다.
	
	fmt.Println(d.String())
}

Console

Age 값이 5 증가한 것을 볼 수 있다.

profile
https://github.com/askePhoenix

0개의 댓글