# 如何遍历不同结构类型的值并在每个值上调用相同的方法？

[英]How can I loop over values of different struct types and call the same method on each?

``````package main

import (
"fmt"
"math"
)

type Rect struct {
width  float64
height float64
}

type Circle struct {
}

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

func (c Circle) Area() float64 {
}

func main() {
rect := Rect{5.0, 4.0}
cir := Circle{5.0}
fmt.Printf("Area of rectangle rect = %0.2f\n", rect.Area())
fmt.Printf("Area of circle cir = %0.2f\n", cir.Area())
}
``````

``````shapes := []interface{ Area() float64 }{Rect{5.0, 4.0}, Circle{5.0}}
for _, shape := range shapes {
fmt.Printf("Area of %T = %0.2f\n", shape, shape.Area())
}
``````

``````type Shape interface {
Area() float64
}
``````

``````    shapes := []Shape{
Rect{5.0, 4.0},
Circle{5.0},
}
``````

``````    for _, shape := range shapes {
// Do something with shape
}
``````

``````    areas := make(chan float64)
for _, shape := range shapes {
currentShape := shape
go func() { areas <- currentShape.Area() }()
}
for i := 0; i < len(shapes); i++ {
fmt.Printf("Area of shape = %0.2f\n", <-areas)
}
``````