Go: Interface

오병민·2021년 6월 14일
0

go

목록 보기
5/7
post-thumbnail

1. Interfaces

Interface 는 method 들의 집합체이다.

Interface 타입의 값은 interface 가 가진 methods 를 구현한 어떠한 값이라도 들어갈 수 있다.

Interface 는 implements 라는 키워드를 사용하지 않고 methods를 만들어서 구현합니다.

아래 예제는 A Tour of Go 에서 가져온 예제다

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

2. Empty interface

interface 가 특정한 methods 를 포함하고 있지 않으면 empty interface 라고 불린다.

interface{}

empty interface 는 어떤 타입의 값을 가지고 있을 수 있다.

알 수없는 타입의 값을 처리하는데 쓰인다. 예를 들면 fmt.Print 함수를 보면 매개변수에 interface{} 를 타입으로 받고 있다.

package main

import "fmt"

func main() {
	var i interface{}
	describe(i)

	i = 42
	describe(i)

	i = "hello"
	describe(i)
}

func describe(i interface{}) {
	fmt.Printf("(%v, %T)\n", i, i)
}

출력
(nil, nil)
(42, int)
(hello, string)

profile
안녕하세요

0개의 댓글