
프로그래밍 언어
Go InterfacesGo 인터페이스
Go 인터페이스(Interface)는 메서드 시그니처의 집합으로, 암묵적(implicit) 구현 방식을 사용한다. 명시적 선언 없이 메서드만 구현하면 인터페이스를 만족한다.
인터페이스 기본
go
type Animal interface {
Name() string
Sound() string
}
type Dog struct{ name string }
func (d Dog) Name() string { return d.name }
func (d Dog) Sound() string { return "멍멍" }
// Dog는 Animal 인터페이스를 암묵적으로 구현
var a Animal = Dog{name: "Rex"}
fmt.Println(a.Name(), a.Sound())빈 인터페이스와 타입 단언
go
// interface{} (any): 모든 타입
func printAny(v interface{}) {
fmt.Printf("값: %v, 타입: %T
", v, v)
}
// 타입 단언
var i interface{} = "hello"
s, ok := i.(string)
if ok { fmt.Println(s) }
// 타입 스위치
func describe(i interface{}) string {
switch v := i.(type) {
case int: return fmt.Sprintf("정수: %d", v)
case string: return fmt.Sprintf("문자열: %s", v)
case bool: return fmt.Sprintf("불리언: %t", v)
default: return fmt.Sprintf("기타: %T", v)
}
}인터페이스 조합
go
type Reader interface { Read(p []byte) (n int, err error) }
type Writer interface { Write(p []byte) (n int, err error) }
// 인터페이스 임베딩으로 조합
type ReadWriter interface {
Reader
Writer
}
type Closer interface { Close() error }
type ReadWriteCloser interface {
ReadWriter
Closer
}작은 인터페이스 설계 원칙
go
// 표준 라이브러리 예시: 단일 메서드 인터페이스
type Stringer interface { String() string }
type Error interface { Error() string }
type Handler interface { ServeHTTP(ResponseWriter, *Request) }
// 의존성 역전: 사용하는 곳에서 인터페이스 정의
type DataStore interface {
GetUser(id int) (*User, error)
}
func NewService(db DataStore) *Service { ... }
