type 인터페이스명 interface {}
인터페이스는 메서드의 집합이다. 단, 메서드 자체를 구현하지는 않는다.
인터페이스 선언하는 방법은 변수 선언법과 같다.
type 인터페이스명 interface {
메서드1() 리턴값_자료명
메서드2() //리턴값이 없을 때
}
주의할 점은 메서드를 ,로 구분하지 않는다는 것이다.
예제)
package main
import (
"fmt"
"math"
)
//인터페이스 선언
type Abser interface {
Abs() float64
}
func main() {
var a Abser
f := MyFloat(-math.Sqrt2)
v := Vertex{3, 4}
a = f // a MyFloat implements Abser
a = &v // a *Vertex implements Abser
// In the following line, v is a Vertex (not *Vertex)
// and does NOT implement Abser.
a = v
fmt.Println(a.Abs())
}
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)
}
댓글 없음:
댓글 쓰기