接口与反射

Go 教程 · 第 6 章 · 8 次浏览

接口(interface)定义一组方法签名,任何实现了这些方法的类型都自动满足接口——这是 Go 的"鸭子类型":不用显式声明实现关系。

接口定义

type Shape interface { Area() float64 }。结构体实现了 Area() 就自动是 Shape。

空接口

interface{}(现在写 any)可以装任何类型,类似 Java 的 Object。用类型断言取回:v, ok := x.(int)。

反射

reflect 包运行时检查类型信息,一般库开发才用,业务代码少碰。

代码示例

package main

import "fmt"

// 接口
type Shape interface {
    Area() float64
}

type Circle struct{ R float64 }
type Rect struct{ W, H float64 }

func (c Circle) Area() float64 { return 3.14159 * c.R * c.R }
func (r Rect) Area() float64   { return r.W * r.H }

func printArea(s Shape) {
    fmt.Printf("面积: %.2f\n", s.Area())
}

func main() {
    printArea(Circle{R: 2})
    printArea(Rect{W: 3, H: 4})

    // 空接口 + 类型断言
    var v any = "hello"
    if s, ok := v.(string); ok {
        fmt.Println("是字符串:", s)
    }
}