1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| package main
import "fmt"
type Any interface{}
func inspectType(i Any) {
fmt.Printf("%v (类型: %T) -> ", i, i)
switch v := i.(type) {
case nil:
fmt.Println("nil值")
case int:
fmt.Printf("整数: %d (两倍=%d)\n", v, v*2)
case string:
fmt.Printf("字符串: %q (长度=%d)\n", v, len(v))
case float64:
fmt.Printf("浮点数: %.2f\n", v)
case bool:
fmt.Printf("布尔值: %t\n", v)
default:
fmt.Printf("其他类型: %T\n", v)
}
}
func main() {
values := []Any{nil, 42, 7, "hi", true, 3.14}
fmt.Println("=== type switch ===\n")
for _, v := range values {
inspectType(v)
}
// <nil> (类型: <nil>) -> nil值
// 42 (类型: int) -> 整数: 42 (两倍=84)
// 7 (类型: int) -> 整数: 7 (两倍=14)
// hi (类型: string) -> 字符串: "hi" (长度=2)
// true (类型: bool) -> 布尔值: true
// 3.14 (类型: float64) -> 浮点数: 3.14
}
|