1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| package main
import ( "math" "fmt" )
type Shape interface { perimeter() float64 area() float64 }
type Rectangle struct { a, b float64 }
type Triangle struct { a, b, c float64 }
type Circle struct { radius float64 }
func (r Rectangle) perimeter() float64 { return (r.a + r.b) * 2 }
func (r Rectangle) area() float64 { return r.a * r.b }
func (t Triangle) perimeter() float64 { return t.a + t.b + t.c }
func (t Triangle) area() float64 {
p := t.perimeter() / 2 return math.Sqrt(p * (p - t.a) * (p - t.b) * (p - t.c)) }
func (c Circle) perimeter() float64 { return 2 * math.Pi * c.radius }
func (c Circle) area() float64 { return math.Pow(c.radius, 2) * math.Pi }
func getType(s Shape) { if instance, ok := s.(Rectangle); ok { fmt.Printf("矩形:长度%.2f , 宽度%.2f , ", instance.a, instance.b) } else if instance, ok := s.(Triangle); ok { fmt.Printf("三角形:三边分别:%.2f , %.2f , %.2f , ", instance.a, instance.b, instance.c) } else if instance, ok := s.(Circle); ok { fmt.Printf("圆形:半径%.2f , ", instance.radius) } }
func getType2(s Shape) { switch instance := s.(type) { case Rectangle: fmt.Printf("矩形:长度为%.2f , 宽为%.2f ,\t", instance.a, instance.b) case Triangle: fmt.Printf("三角形:三边分别为%.2f ,%.2f , %.2f ,\t", instance.a, instance.b, instance.c) case Circle: fmt.Printf("圆形:半径为%.2f ,\t", instance.radius) } }
func getResult(s Shape) { getType2(s) fmt.Printf("周长:%.2f ,面积:%.2f \n", s.perimeter(), s.area()) }
func main() { var s Shape s = Rectangle{3, 4} getResult(s) showInfo(s)
s = Triangle{3, 4, 5} getResult(s) showInfo(s)
s = Circle{1} getResult(s) showInfo(s)
x := Triangle{3, 4, 5} fmt.Println(x)
}
func (t Triangle) String() string { return fmt.Sprintf("Triangle对象,属性分别为:%.2f, %.2f, %.2f", t.a, t.b, t.c) }
func showInfo(s Shape) { fmt.Printf("%T ,%v \n", s, s) fmt.Println("-------------------") }
|