ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Go - Interface
    Engineering WIKI/GoLang 2021. 1. 19. 06:05
    '''
    구조체(struct)가 필드들의 집합체라면, interface는 메서드들의 집합체이다. 
    interface는 타입(type)이 구현해야 하는 메서드 원형(prototype)들을 정의한다. 
    하나의 사용자 정의 타입이 interface를 구현하기 위해서는 단순히 그 인터페이스가 갖는 
    모든 메서드들을 구현하면 된다.
    
    인터페이스는 struct와 마찬가지로 type 문을 사용하여 정의한다.
    '''
    
    type Shape interface {
        area() float64
        perimeter() float64
    }
    //Rect 정의
    type Rect struct {
        width, height float64
    }
     
    //Circle 정의
    type Circle struct {
        radius float64
    }
     
    //Rect 타입에 대한 Shape 인터페이스 구현 
    func (r Rect) area() float64 { return r.width * r.height }
    func (r Rect) perimeter() float64 {
         return 2 * (r.width + r.height)
    }
     
    //Circle 타입에 대한 Shape 인터페이스 구현 
    func (c Circle) area() float64 { 
        return math.Pi * c.radius * c.radius
    }
    func (c Circle) perimeter() float64 { 
        return 2 * math.Pi * c.radius
    }

    'Engineering WIKI > GoLang' 카테고리의 다른 글

    Go - Map  (0) 2021.01.19
    Go - Slice  (0) 2021.01.19
    Go - Array  (0) 2021.01.19
    [GO] GO Run, Build, Install  (0) 2020.05.30
Designed by Tistory.