PHpullh
학습 라이브러리/Go/인터페이스 — 덕 타이핑

GO · 구조체/인터페이스

인터페이스 — 덕 타이핑

Go 인터페이스는 암묵적으로 구현됩니다. 선언 없이 메서드만 맞으면 됩니다.

구조체/인터페이스중급interfaceduck-typing암묵적구현type-assertionempty-interface

핵심 설명

Go 인터페이스는 암묵적으로 구현됩니다. 선언 없이 메서드만 맞으면 됩니다.

Go code

package main

import (
	"fmt"
	"math"
)

// 인터페이스 정의
type Shape interface {
	Area() float64
	Perimeter() float64
}

// Stringer 인터페이스 (fmt.Stringer)
type Stringer interface {
	String() string
}

// 구현체 — 명시적 선언 없음
type Rectangle struct{ W, H float64 }
func (r Rectangle) Area() float64      { return r.W * r.H }
func (r Rectangle) Perimeter() float64 { return 2*(r.W+r.H) }
func (r Rectangle) String() string {
	return fmt.Sprintf("Rect(%.1f×%.1f)", r.W, r.H)
}

type Circle struct{ R float64 }
func (c Circle) Area() float64      { return math.Pi * c.R * c.R }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.R }

// 인터페이스를 파라미터로
func printShape(s Shape) {
	fmt.Printf("넓이: %.2f, 둘레: %.2f
", s.Area(), s.Perimeter())
}

// 인터페이스 슬라이스
func totalArea(shapes []Shape) float64 {
	var total float64
	for _, s := range shapes { total += s.Area() }
	return total
}

// 빈 인터페이스 — 모든 타입 허용
func describe(i interface{}) {
	fmt.Printf("타입: %T, 값: %v
", i, i)
}

// 타입 단언
func main() {
	shapes := []Shape{
		Rectangle{3, 4},
		Circle{5},
	}
	for _, s := range shapes { printShape(s) }
	fmt.Printf("총 넓이: %.2f
", totalArea(shapes))

	describe(42)
	describe("hello")
	describe(Rectangle{1, 2})

	// 타입 단언
	var s Shape = Rectangle{3, 4}
	if r, ok := s.(Rectangle); ok {
		fmt.Println("Rectangle:", r.W, r.H)
	}
}

학습 팁

작은 인터페이스가 좋습니다. Go 표준 라이브러리의 io.Reader(메서드 1개), io.Writer(메서드 1개)가 대표 예시입니다.

주의할 점

인터페이스 값이 nil인지 확인할 때 주의: 인터페이스가 nil 포인터를 담고 있으면 i == nil은 false입니다. 타입과 값이 모두 nil이어야 interface nil입니다.

자주 묻는 질문

인터페이스 — 덕 타이핑란 무엇인가요?

Go 인터페이스는 암묵적으로 구현됩니다. 선언 없이 메서드만 맞으면 됩니다.

인터페이스 — 덕 타이핑 학습 시 주의할 점은 무엇인가요?

인터페이스 값이 nil인지 확인할 때 주의: 인터페이스가 nil 포인터를 담고 있으면 i == nil 은 false입니다. 타입과 값이 모두 nil이어야 interface nil입니다.