🔥 인터페이스 타입
279자
3분
Go 언어에서 인터페이스 타입은 메서드 시그니처의 집합으로 정의됩니다. 인터페이스 타입의 값은 해당 메서드를 구현하는 모든 값을 저장할 수 있죠.
예를 들어, 다음과 같이 Abser 인터페이스를 정의할 수 있습니다.
go
type Abser interface {
Abs() float64
}
go
type Abser interface {
Abs() float64
}
Abser 인터페이스는 Abs() float64 메서드 시그니처를 가지고 있습니다. 이 인터페이스를 구현하는 타입은 Abs() float64 메서드를 반드시 구현해야 합니다.
이제 MyFloat와 *Vertex 타입이 Abser 인터페이스를 구현하는 예제 코드를 살펴보겠습니다.
go
type MyFloat float64
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
type Vertex struct {
X, Y float64
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
go
type MyFloat float64
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
type Vertex struct {
X, Y float64
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
MyFloat타입은Abs() float64메서드를 구현하여Abser인터페이스를 만족합니다.Vertex타입도Abs() float64메서드를 구현하므로Abser인터페이스를 만족하죠.
하지만 Vertex 타입(값 타입)은 Abs() float64 메서드를 구현하지 않았기 때문에 Abser 인터페이스를 만족하지 않습니다.
이제 main 함수에서 인터페이스를 사용하는 방법을 알아보겠습니다.
go
func main() {
var a Abser
f := MyFloat(-math.Sqrt2)
v := Vertex{3, 4}
a = f // a MyFloat implements Abser
fmt.Println(a.Abs()) // 1.4142135623730951
a = &v // a *Vertex implements Abser
fmt.Println(a.Abs()) // 5
// In the following line, v is a Vertex (not *Vertex)
// and does NOT implement Abser.
a = v // 컴파일 에러 발생!
}
go
func main() {
var a Abser
f := MyFloat(-math.Sqrt2)
v := Vertex{3, 4}
a = f // a MyFloat implements Abser
fmt.Println(a.Abs()) // 1.4142135623730951
a = &v // a *Vertex implements Abser
fmt.Println(a.Abs()) // 5
// In the following line, v is a Vertex (not *Vertex)
// and does NOT implement Abser.
a = v // 컴파일 에러 발생!
}
a는Abser인터페이스 타입의 변수입니다.f는MyFloat타입의 값이고,MyFloat는Abser인터페이스를 구현하므로a = f는 유효합니다.&v는Vertex타입의 값이고,Vertex는Abser인터페이스를 구현하므로a = &v도 유효하죠.- 하지만
v는Vertex타입의 값이고,Vertex는Abser인터페이스를 구현하지 않으므로a = v는 컴파일 에러를 발생시킵니다.
이렇게 인터페이스를 사용하면 서로 다른 타입의 값을 동일한 인터페이스 타입으로 다룰 수 있어 코드의 유연성과 확장성을 높일 수 있습니다.









