Golang 삼위일체: 함수, 메서드, 인터페이스
Source: Dev.to
함수
함수는 주어진 입력으로 연산을 수행합니다.
// Function
func Add(a, b int) int { return a + b }
메서드
메서드는 수신자를 가진 함수로, 특정 타입에 동작을 부착합니다.
type Counter struct{ val int }
// Method (receiver is the "attachment")
인터페이스
인터페이스는 타입이 구현해야 하는 메서드 집합을 정의합니다. 타입은 자동으로 인터페이스를 만족하므로, 명시적인 implements 키워드나 상속이 필요하지 않습니다.
type Stringer interface {
// method signatures go here
}
type User struct{ Name string }
// User now implements Stringer automatically
func Print(s Stringer) { fmt.Println(s.String()) }
트위스트: 함수가 인터페이스가 될 수 있다
함수 타입에 메서드를 부여하면 해당 인터페이스를 만족시킬 수 있습니다. 이 패턴은 종종 혼란을 줍니다.
// An interface
type Handler interface {
Handle(string)
}
// A function type
type HandleFunc func(string)
// The trick: attach the Handle method to the function type
func (hf HandleFunc) Handle(s string) { hf(s) }
// Now any function with signature func(string) works as a Handler
모두 합쳐 보기
함수, 메서드, 인터페이스를 조합합니다:
type Greeter interface { Greet() string }
type Person struct{ Name string }
type GreetFunc func() string
func (gf GreetFunc) Greet() string { return gf() }
func Party(g Greeter) { fmt.Println(g.Greet()) }
func main() {
p := Person{Name: "Alice"}
greet := GreetFunc(func() string { return "Hello, " + p.Name })
Party(greet)
}
요약
- 함수는 프로그램 흐름을 조율합니다.
- 메서드는 특정 타입에 동작을 정의합니다.
- 인터페이스는 무엇을 할지와 어떻게 할지를 분리하여, 서로 다른 타입을 교체 가능하게 합니다.
여러분의 차례
아래에 여러분만의 예시나 질문을 남겨 주세요 👇