62 lines
1.0 KiB
Go
Raw Normal View History

2025-04-08 17:01:19 +08:00
package main
2025-04-10 17:45:32 +08:00
import "fmt"
// 定义一个接口
type Shape interface {
Area() float64
}
// 定义一个结构体Rectangle
type Rectangle struct {
Width, Height float64
}
// 实现接口方法Area
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// 定义另一个结构体Circle
type Circle struct {
Radius float64
}
// 实现接口方法Area
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
2025-04-08 17:01:19 +08:00
func main() {
2025-04-10 17:45:32 +08:00
// 创建接口类型的切片
shapes := []Shape{
Rectangle{Width: 10, Height: 5},
Circle{Radius: 7},
}
shapes2 := []Shape{
Rectangle{Width: 20, Height: 10},
Circle{Radius: 14},
Rectangle{Width: 30, Height: 15},
Rectangle{5, 5},
}
// 遍历并调用接口方法
for _, shape := range shapes {
fmt.Printf("Shape Area: %.2f\n", shape.Area())
}
// i := 0
// for {
// fmt.Printf("Shape Area: %.2f\n", shapes2[i].Area())
// i++
// if i >= len(shapes2) {
// break
// }
// }
for _, shape := range shapes2 {
fmt.Printf("%.2f\n", shape.Area())
}
2025-04-08 17:01:19 +08:00
}