Skip to content

Commit bb9fef2

Browse files
committed
lesson22
1 parent f12ec3c commit bb9fef2

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

lesson22/main.go

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"reflect"
6+
)
7+
8+
//func reflectType(x interface{}) {
9+
// obj := reflect.TypeOf(x)
10+
// fmt.Println(obj)
11+
//}
12+
13+
//func reflectType(x interface{}) {
14+
// typeX := reflect.TypeOf(x)
15+
// valueX := reflect.ValueOf(x)
16+
// fmt.Println(typeX)
17+
// fmt.Println(valueX)
18+
//}
19+
20+
func reflectType(x interface{}) {
21+
typeX := reflect.TypeOf(x)
22+
fmt.Println(typeX.Kind())
23+
fmt.Println(typeX)
24+
}
25+
26+
func main() {
27+
//var a int64 = 123
28+
//reflectType(a)
29+
//var b string = "从0到Go语言微服务架构师"
30+
//reflectType(b)
31+
/*
32+
reflect.Type 表示interface{}的具体类型
33+
reflect.TypeOf()返回reflect.Type
34+
*/
35+
36+
//reflect.Kind()
37+
//var book book
38+
//reflectType(book)
39+
//reflectNumField(book)
40+
41+
//var book = book{
42+
// name: "《Go语言极简一本通》",
43+
// target: "学习Go语言语法,并可以单独完成一个单体服务。",
44+
// spend: 8,
45+
//}
46+
//reflectNumField(book)
47+
48+
//反射第一定律- 反射可以将"接口类型变量"转换为"反射类型变量"
49+
var a interface{} = 3.14
50+
fmt.Printf("接口变量的类型为 %T,值为 %v\n", a, a)
51+
t := reflect.TypeOf(a)
52+
v := reflect.ValueOf(a)
53+
fmt.Printf("从接口变量到反射对象:Type对象类型为 %T\n", t)
54+
fmt.Printf("从接口变量到反射对象:Value对象类型为 %T\n", v)
55+
56+
//反射第二定律- 反射可以将"反射类型对象"转换为"接口对象"
57+
58+
i := v.Interface()
59+
fmt.Printf("从反射对象到接口变量:对象类型%T,值为%v\n", i, i)
60+
//使用类型断言进行转换
61+
x := v.Interface().(float64)
62+
fmt.Printf("x的类型为 %T,值为 %v\n", x, x)
63+
64+
//反射第二定律- 如果要修改"反射类型对象"其值必须是"可写的"
65+
var c float64 = 3.14
66+
y := reflect.ValueOf(&c).Elem()
67+
fmt.Println("是否可写:", y.CanSet())
68+
y.SetFloat(2.1)
69+
fmt.Println(y)
70+
}
71+
72+
//func reflectNumField(x interface{}) {
73+
// if reflect.ValueOf(x).Kind() == reflect.Struct {
74+
// v := reflect.ValueOf(x)
75+
// fmt.Println("Number of fields", v.NumField())
76+
// }
77+
//}
78+
79+
func reflectNumField(x interface{}) {
80+
if reflect.ValueOf(x).Kind() == reflect.Struct {
81+
v := reflect.ValueOf(x)
82+
fmt.Println("Number of fields", v.NumField())
83+
for i := 0; i < v.NumField(); i++ {
84+
fmt.Printf("Field:%d type:%T value:%v\n", i, v.Field(i), v.Field(i))
85+
}
86+
}
87+
}
88+
89+
type book struct {
90+
name string
91+
target string
92+
spend int
93+
}

0 commit comments

Comments
 (0)