Golang 삼위일체: 함수, 메서드, 인터페이스

발행: (2026년 5월 28일 AM 10:32 GMT+9)
3 분 소요
원문: Dev.to

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)
}

요약

  • 함수는 프로그램 흐름을 조율합니다.
  • 메서드는 특정 타입에 동작을 정의합니다.
  • 인터페이스무엇을 할지와 어떻게 할지를 분리하여, 서로 다른 타입을 교체 가능하게 합니다.

여러분의 차례

아래에 여러분만의 예시나 질문을 남겨 주세요 👇

0 조회
Back to Blog

관련 글

더 보기 »

첫 포스트: 짧은 전기

Introduction Hello, my name is Jay. Growing up, I wanted to follow in my dad's footsteps and become an engineer—and I did, just not in the way I originally exp...