Golang

[Golang] 인터페이스

GenieLove! 2022. 3. 16. 00:34
728x90
반응형

1.인터페이스  선언

(1)인터페이스에 포함된 메소드 유의 사항

①메소드는 반드시 메소드명이 있어야 한다.

②매개변수, 반환 값이 달라도 메소드 명이 중복되어서는 안 된다.

③인터페이스에서는 메소드 구현을 포함하지 않는다(밖에서 선언된 메소드여야 한다.)

type 인터페이스명 interface {
	인터페이스에_포함된_메소드명1() 리턴타입
    인터페이스에_포함된_메소드명2()//리턴값이 없는 경우 비어놓음
}

(2)사용 예시1

type Stringer interface {
	String() string
}

type User struct {
	Name	string
    ID		string
}

func (u User) String() string {//포인터 사용X
	return u.Name
}

func main() {
	user := User{"genie", "genieID"}
    
    var stringer Stringer
    stringer = user
    fmt.Println(stringer.String())
}

(3)사용 예시2

package main

import "fmt"

type Animal interface {
	Talk()
	LegCount() int
}

type Person struct {
	Name string
	Leg  int
	Age  int
}

func (p Person) Talk() {
	fmt.Println("사람말~~")
}

func (p Person) LegCount() int {
	return p.Leg
}

type Dog struct {
	Name string
	Leg  int
}

func (d Dog) Talk() {
	fmt.Println("강아지 말~")
}

func (d Dog) LegCount() int {
	return d.Leg
}

func main() {
	person := Person{Name: "soomin", Leg: 2, Age: 28}
	dog := Dog{Name: "genie", Leg: 4}

	var animal Animal
	animal = person
	animal.Talk()
	fmt.Println(animal.LegCount())

	animal = dog
	animal.Talk()
	fmt.Println(animal.LegCount())
	dogStruct := animal.(Dog)
	fmt.Println(dogStruct)
}

2.덕 타이핑

- 타입 선언 시 인터페이스 구현 여부를 명시적으로 나타낼 필요없이 인터페이스에 정의한 메소드 포함 여부만으로 결정하는 방식

(1)예시

package main

import "fmt"

type Animal interface {
	Talk()
	LegCount() int
}

//별다른 명시 없이 Talk(), LegCount()를 포함한 것으로 Animal 인터페이스 사용할 수 있음
//interface에 선언된 메소드를 모두 포함하고 있어야 함
//덕 타이핑이 없었으면 type Person struct implements Animal이 되었을 것
type Person struct {
	Name string
	Leg  int
	Age  int
}

func (p Person) Talk() {
	fmt.Println("사람말~~")
}

func (p Person) LegCount() int {
	return p.Leg
}


func main() {
	person := Person{Name: "soomin", Leg: 2, Age: 28}
	
	var animal Animal
	animal = person
	animal.Talk()
	fmt.Println(animal.LegCount())
}

3.인터페이스 추가 기능

(1)인터페이스를 포함한 인터페이스

type Reader interface {
	Read() (n int, err error)
    Close() error
}

type Writer interface {
	Write() (n int, err error)
    Close() error
}

type ReadWriter interface {
	Reader//Reader의 메소드 집합 포함
    Writer
}

(2)빈 인터페이스 파라미터

예시

func PrintParam(param interface{}) {
	switch t := param.(type) {
    case int:
    	fmt.Printf("type : int %d", int(t))
    case float64:
    	fmt.Printf("type : float64 %f", float64(t))
    case string:
    	fmt.Printf("type : string %s", string(t))
    default:
    	fmt.Printf("type : %T %v", t, t)
    }
}

(3)인터페이스 기본 값 - nil

 

4.인터페이스 타입 변환

(1)구체화된 다른 타입으로 변환(변수.(타입) 으로 사용)

var num Interface
t := num.(int)

(2)다른 인터페이스로 타입 변환

type Reader interface {
	Read()
}

type Closer interface {
	Close()
}

type File struct {
}

func (f *File) Read() {
}

func ReadFile(reader Reader) {
	c := reader.(Closer)//런타임 에러 <- 실질적으로 받는 File객체엔 Closer인터페이스가 존재하지 않는다.
    c.Close()
}

func main() {
	file := &File{}
    ReadFile(file)
}

(3)타입 변환 성공 여부

var num Interface
t, ok := num(int)//타입 변환한 값, 변환 성공 여부
728x90
반응형

'Golang' 카테고리의 다른 글

[Golang] 자료구조  (0) 2022.03.23
[Golang] 함수  (1) 2022.03.21
[Golang] 메소드  (0) 2022.03.12
[Golang] 슬라이스  (0) 2022.03.04
[Golang] 패키지  (0) 2022.02.27