# 空接口与类型断言

URL: https://caijiao.org/go/03-structured/08-empty-interface
Source: docs/go/03-structured/08-empty-interface.md
Description: 本节介绍 Go 语言中的空接口及类型断言，帮助处理任意类型数据和动态类型转换。

## 1. 空接口（interface{}）

空接口没有任何方法，所有类型都实现了空接口，因此空接口可以存储任意类型的值。

```go
var x interface{}
x = 42
x = "hello"
x = struct{ Name string }{Name: "Go"}
````

## 2. 类型断言

从接口变量中提取具体类型的值，使用类型断言：

```go
var x interface{} = "hello"

s, ok := x.(string)
if ok {
    fmt.Println("字符串值:", s)
} else {
    fmt.Println("不是字符串")
}
```

断言失败时，`ok` 为 `false`，防止运行时错误。

## 3. 类型开关

使用 `switch` 语句对接口类型进行多路判断：

```go
switch v := x.(type) {
case int:
    fmt.Println("整数", v)
case string:
    fmt.Println("字符串", v)
default:
    fmt.Println("其他类型")
}
```

---

空接口和类型断言支持动态类型处理，是 Go 语言灵活性的关键。
