[Golang] receiver

SangHun·2021년 9월 5일
0

Golang 공부를 하다가 매우 희안한 코드를 발견했다...

type Lexer struct {
    input string
    position int
    readPosition int
    ch byte
}

func (l *Lexer) readChar(){
    ...
}

문제의 코드는 아래쪽의 함수 readChar()이다.
Go 함수의 parameter나 return type은 분명 함수명 뒤에 주르륵 나오는데,
함수명 앞에 있는 이 (l *Lexer) 녀석은 무엇인고??

고알못으로서 구글링 해본 결과
receiver라는 걸 알게되었다.

아시다시피 Golang에는 Class가 없다(!)
때문에, 구조체Structure로 모두 해결해야 한다.
이 때 함수를 Class method 처럼 사용케 해주는 것이 이 receiver다.
이 method가 속한 struct 타입과 struct 변수명으로 receiver를 지정해준다.

위처럼 코드를 작성하면

l := Lexer{input: "dummy string"}
l.readChar()

이처럼 사용할 수 있다.

profile
개발괴발자

0개의 댓글