haonly / Go-go-go

Golang study for 카린이
2 stars 1 forks source link

[STUDY_LOG] 2021.03.08 #14

Open haonly opened 3 years ago

haonly commented 3 years ago

TITLE


CONTENTS 인터페이스

import ( "fmt" "math" )

type geometry interface { area() float64 perimeter() float64 // 둘레를 측정하는 메소드 추가 }

type Rect struct { width, height float64 }

type Circle struct { radius float64 }

func (r Rect) area() float64 { return r.width * r.height }

func (c Circle) area() float64 { return math.Pi c.radius c.radius }

func (r Rect) perimeter() float64 { // 둘레를 측정하는 메소드 추가 return 2 * (r.width + r.height) }

func (c Circle) perimeter() float64 { // 둘레를 측정하는 메소드 추가 return 2 math.Pi c.radius }

func main() { r1 := Rect{10, 20} c1 := Circle{10} r2 := Rect{12, 14} c2 := Circle{5}

printMeasure(r1, c1, r2, c2)

}

func printMeasure(m ...geometry) { for _, val := range m { fmt.Println(val) fmt.Println(val.area()) fmt.Println(val.perimeter()) } }


- Type Assertion
  - 인터페이스가 dynamic type이기 때문에 확실항 형 표현을 위해 type assertion을 해 줄 필요가 있음
  - **`변수이름.(형)`** 으로 사용
  - 

---

**Additional context**
오늘은.. 진짜 하기 싫었는데.. 그래도 하나만 했음...
haonly commented 3 years ago

연습문제

package main

import (
    "fmt"
    "math"
)

type geometry interface{
    area() float32
    volume() float32
}

type Cylinder struct{
    r, h float32
}

type Cuboid struct{
    a, b, c float32
}

func (cy Cylinder) area() float32{
    return ((math.Pi*cy.r*cy.r)*2 + (2*math.Pi*cy.r*cy.h))
}

func (cy Cylinder) volume() float32{
    return (math.Pi*cy.r*cy.r)*cy.h
}

func (cu Cuboid) area() float32{
    return 2*cu.a*cu.b + 2*cu.a*cu.c + 2*cu.b*cu.c
}

func (cu Cuboid) volume() float32{
    return cu.a*cu.b*cu.c
}

func main() {
    cy1 := Cylinder{10, 10}
    cy2 := Cylinder{4.2, 15.6}
    cu1 := Cuboid{10.5, 20.2, 20}
    cu2 := Cuboid{4, 10, 23}

    printMeasure(cy1, cy2, cu1, cu2)    
}

func printMeasure(m ...geometry) {
    for _, val := range m{
        fmt.Printf("%.2f, %.2f\n", val.area(), val.volume())

    }
}