interfaces.go 890 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. // 1. 接口:只要实现了 Area() float64 就是 Shape
  7. type Shape interface {
  8. Area() float64
  9. }
  10. // 2. 矩形
  11. type Rect struct {
  12. W, H float64
  13. }
  14. // 3. 圆
  15. type Circle struct {
  16. R float64
  17. }
  18. // 4. 隐式实现:Rect 有了 Area() float64 → 自动变成 Shape
  19. func (r Rect) Area() float64 {
  20. return r.W * r.H
  21. }
  22. // 5. 隐式实现:Circle 同理
  23. func (c Circle) Area() float64 {
  24. return math.Pi * c.R * c.R
  25. }
  26. // 6. 统一打印面积:多态
  27. func printArea(s Shape) {
  28. fmt.Printf("面积 = %.2f\n", s.Area())
  29. }
  30. func main() {
  31. // 7. 接口变量可以装任何实现者
  32. var s Shape
  33. s = Rect{3, 4}
  34. printArea(s) // 12.00
  35. s = Circle{R: 2}
  36. printArea(s) // 12.57
  37. // 8. 空接口:万能容器(类似 Python 的 object)
  38. var box interface{}
  39. box = 42
  40. box = "hello"
  41. box = Rect{1, 1}
  42. fmt.Println("空接口里装的是:", box)
  43. }