| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- package main
- import (
- "fmt"
- "math"
- )
- // 1. 接口:只要实现了 Area() float64 就是 Shape
- type Shape interface {
- Area() float64
- }
- // 2. 矩形
- type Rect struct {
- W, H float64
- }
- // 3. 圆
- type Circle struct {
- R float64
- }
- // 4. 隐式实现:Rect 有了 Area() float64 → 自动变成 Shape
- func (r Rect) Area() float64 {
- return r.W * r.H
- }
- // 5. 隐式实现:Circle 同理
- func (c Circle) Area() float64 {
- return math.Pi * c.R * c.R
- }
- // 6. 统一打印面积:多态
- func printArea(s Shape) {
- fmt.Printf("面积 = %.2f\n", s.Area())
- }
- func main() {
- // 7. 接口变量可以装任何实现者
- var s Shape
- s = Rect{3, 4}
- printArea(s) // 12.00
- s = Circle{R: 2}
- printArea(s) // 12.57
- // 8. 空接口:万能容器(类似 Python 的 object)
- var box interface{}
- box = 42
- box = "hello"
- box = Rect{1, 1}
- fmt.Println("空接口里装的是:", box)
- }
|