Open haonly opened 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())
}
}
TITLE
CONTENTS 인터페이스
var x interface{}
) 어떠한 형도 담을 수 있도록 만들어 줄 수 있음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}
}
func printMeasure(m ...geometry) { for _, val := range m { fmt.Println(val) fmt.Println(val.area()) fmt.Println(val.perimeter()) } }