接口-参考答案

2018-06-18  本文已影响0人  tonyemail_st
package main

import (
    "math"
    "fmt"
)

type geometry interface {
    area() float64
    perim() float64
}

type rect struct {
    width, hight float64
}

type circle struct {
    radius float64
}

func (r rect) area() float64{
    return r.width*r.hight
}

func (r rect) perim() float64  {
    return r.width*2 + r.hight*2
}

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

func (c circle) perim() float64  {
    return 2*math.Pi*c.radius
}

func measure(g geometry){
    fmt.Println(g)
    fmt.Println(g.area())
    fmt.Println(g.perim())
}


func main(){
    r := rect{2,4}
    c := circle{4}
    measure(r)
    measure(c)
}
上一篇下一篇

猜你喜欢

热点阅读