286_尚硅谷_反射的快速入门(2)
1.反射的快速入门和常量介绍
2.2. 请编写一个案例,演示对(结构体类型、interface{、reflect.Value)进行反射的基本操作_代码
package main
import (
"fmt"
"reflect"
)
type Student struct {
Name string
Age int
}
// todo 专门演示反射【对结构体的反射】
func reflectTest02(stu_struct interface{}) {
// * 1. 先获取到 reflect.Type【反射类型】, 使用reflect.TypeOf()方法
rType := reflect.TypeOf(stu_struct)
fmt.Println(rType)
// * 2. 获取到 reflect.Value【反射值】, 使用reflect.ValueOf()方法
rVal := reflect.ValueOf(stu_struct)
// * 3. 将rVal转成interface{}类型, 但是取不了结构体里的字段内容, iV.Name会报错
iV := rVal.Interface()
fmt.Printf("iV= %v, iV type= %T\n", iV, iV)
// * 4. 将interface{}通过类型断言转成原来的类型,即结构体【测试效果】
// ! 简单使用一个带检测的类型断言, 也可以使用switch 的断言形式来做更加灵活
stu, ok := iV.(Student)
// 类型断言成功
if ok {
fmt.Println("类型断言成功, 可以正常取出结构体字段中的内容, stu.Name= ", stu.Name)
}
}
// todo 2. 请编写一个案例,演示对(结构体类型、interface{、reflect.Value)进行反射的基本操作
func main() {
// 2. 定义一个Student的实例
stu := Student{
Name: "tom",
Age: 20,
}
reflectTest02(stu)
}
3.2. 请编写一个案例,演示对(结构体类型、interface{、reflect.Value)进行反射的基本操作_运行结果
4.2常量申明的时候,必须赋值
package main
import (
"fmt"
)
func main() {
var num int
// ! 2. 常量声明的时候, 必须赋值
const tax int
fmt.Println(num, tax)
}
5.3.常量赋值后不能修改
6.常量使用注意事项:2.专业写法
浙公网安备 33010602011771号