289_尚硅谷_反射的练习题

1.反射练习题1.反射练习题

2.1) 一个变量 var v float64 = 1.2,使用反射得到他的reflect.Value, 然后获得对应的Type, Kind和值, 并将reflect.Value 转换成 interface{},再将interface{} 转换成float642.1) 一个变量 var v float64 = 1.2,使用反射得到他的reflect.Value, 然后获得对应的Type, Kind和值, 并将reflect.Value 转换成 interface{},再将interface{} 转换成float64.

package main

import (
	"fmt"
	"reflect"
)

// todo 1) 一个变量 var v float64 = 1.2,使用反射得到他的reflect.Value, 然后获得对应的Type, Kind和值, 并将reflect.Value 转换成 interface{},再将interface{} 转换成float64.
func exec01(b interface{}) {
	// * 1. 使用反射得到他的reflect.Value, 然后获得对应的Type, Kind和值
	vVal := reflect.ValueOf(b)

	// 由于传入的是指针,需要使用 Elem() 获取指针指向的值
	elemVal := vVal.Elem()

	fmt.Printf("使用reflect.ValueOf()方法:\n")
	fmt.Printf("reflect.Value = %v\n", elemVal)
	fmt.Printf("Type = %v\n", elemVal.Type())
	fmt.Printf("Kind = %v\n", elemVal.Kind())
	fmt.Printf("值 = %v\n\n", elemVal.Interface())

	// * 2. 将reflect.Value 转换成 interface{},再将interface{} 转换成float64
	// 将 reflect.Value 转换为 interface{}
	i := elemVal.Interface()
	fmt.Printf("interface{} 值 = %v, 类型 = %T\n", i, i)

	// 将 interface{} 转换为 float64
	if f, ok := i.(float64); ok {
		fmt.Printf("转换后的 float64 值 = %v, 类型 = %T\n\n", f, f)

		// 通过反射修改原变量的值
		elemVal.SetFloat(3.14)
		fmt.Printf("通过反射修改后: ")
	} else {
		fmt.Println("类型转换失败")
	}
}

func main() {
	var v float64 = 1.2
	fmt.Printf("原始值: v = %v\n\n", v)

	exec01(&v)
	fmt.Printf("main函数中: v = %v\n", v)
}

3.1) 一个变量 var v float64 = 1.2,使用反射得到他的reflect.Value, 然后获得对应的Type, Kind和值, 并将reflect.Value 转换成 interface{},再将interface{} 转换成float64_运行结果3.1) 一个变量 var v float64 = 1.2,使用反射得到他的reflect.Value, 然后获得对应的Type, Kind和值, 并将reflect.Value 转换成 interface{},再将interface{} 转换成float64_运行结果

4.判断代码是否正确4.判断代码是否正确

package main

import (
	"fmt"
	"reflect"
)

// todo 判断代码是否正确
// func main() {
// 	var str string = "tom"
// 	fs := reflect.ValueOf(str)
// 	fs.SetString("jack") // ! error
// 	fmt.Printf("%v\n", str)
// }

// * 修改如下
func main() {
	var str string = "tom"
	fs := reflect.ValueOf(&str)
	fmt.Printf("fs= %v, fs_type= %T\n", fs, fs)
	// * reflect.Value类型要使用Elem().SetString()【对应的.Set类型("反射的新值")】
	fs.Elem().SetString("jack")
	fmt.Printf("%v\n", str)
}

posted on 2026-03-09 14:31  与太阳肩并肩  阅读(3)  评论(0)    收藏  举报

导航