본문 바로가기
Go

[Go] receiver 함수

by 강석현 2022. 4. 11.

Go 에서 struct에 속해 있는 함수가 있음.

다른 언어에서의 Method 같은 역할을 함.

이를 receiver 함수라 부름.

 

사용방법

func (변수명 struct_type) 함수명() {}

 

여기서 변수명은 struct_type의 앞자리를 주로 사용.

포인터 사용 가능

 

예시

package main

import "fmt"

type person struct {
  name string
}

func (p person) hello() {
  fmt.Printf("Hello! My name is %s\n", p.name) // Hello! My name is poppy
}

func main() {
  poppy := person{"poppy"}
  poppy.hello()
}

 

 

연관 글

 

Go Struct 생성하기

https://bbugi.tistory.com/5

 

Go Struct 생성하기

type 이름 struct { 변수이름1 타입 변수이름2 타입 ... } 이름을 대문자로 하면 Export 가능. 예문 type Person struct { name string age int }

bbugi.tistory.com

 

Go 콘솔 출력 방법

https://bbugi.tistory.com/8

 

Go 콘솔 출력 방법

fmt 패키지 사용 fmt.Print("Hello\n") fmt.Println("Hello") greeting := "Hello" fmt.Printf("%s\n", greeting) 모두 콘솔에 Hello를 출력하고 한 줄 넘김.

bbugi.tistory.com

 

'Go' 카테고리의 다른 글

[Go] dependency 설치  (0) 2022.04.24
[Go] struct 없이 type 사용  (0) 2022.04.19
[Go] 변수 여러개 선언  (0) 2022.04.08
[Go] 콘솔 출력 방법  (0) 2022.04.07
[Go] Array, Slice 만들기  (0) 2022.03.28

댓글