Go语言中的类型断言

类型断言

类型断言,由于接口是一般类型,不知道具体类型,如果要转成具体类型
可以采用以下方法进行转换:

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
func test1() {
var a interface{}
var b int = 10
a = b
fmt.Printf("a type is %T value is %d\n", a, a)
// 断言
c, ok := a.(int)
if ok == false {
fmt.Println("conversion fail")
return
}
fmt.Printf("c type is %T value is %d\n", c, c)
}

func main() {
test1()
}
------------
a type is int value is 10
c type is int value is 10



type Student struct{}

func assertion(item ...interface{}) {
for i, v := range item {
switch v.(type) {
case bool:
fmt.Printf("%d param is bool value is %v\n", i, v)
case string:
fmt.Printf("%d param is string value is %v\n", i, v)
case float32, float64:
fmt.Printf("%d param is float value is %v\n", i, v)
case int, int32, int64:
fmt.Printf("%d param is int value is %v\n", i, v)
case Student:
fmt.Printf("%d param is Student value is %v\n", i, v)
case *Student:
fmt.Printf("%d param is Student Pointer value is %v\n", i, v)
default:
fmt.Printf("%d param type is unknown value is %v\n", i, v)
}
}
}

func test2() {
var stu Student
assertion(true, stu, 1, 1.2, "test", &Student{})
}

func main() {
test2()
}
--------------
0 param is bool value is true
1 param is Student value is {}
2 param is int value is 1
3 param is float value is 1.2
4 param is string value is test
5 param is Student Pointer value is &{}