Go反射使用记录


原文地址声明:https://blog.csdn.net/qq_23179075/article/details/104295201

Go反射使用记录

type User struct {
	Name   string
	Age    int
}

1. 通过反射方法reflect.New()创建实例

通过reflect.New()创建的实例,总是返回的是实例指针类型。

func ReflectNew(arg interface{}) interface{} {
	if arg == nil {
		return nil
	}
	typeOf := reflect.TypeOf(arg)
	//判断指针类型
	if typeOf.Kind() == reflect.Ptr {
		typeOf = typeOf.Elem()
	}

	now := reflect.New(typeOf)
	////设置字段值
	//now.Elem().FieldByName("Name").Set(reflect.ValueOf("张三"))
	//now.Elem().FieldByName("Age").Set(reflect.ValueOf(24))
	return now.Interface()
}

func TestReflectNew(t *testing.T) {
	//instance := ReflectNew(&User{})
	instance := ReflectNew(User{})
	user := instance.(*User)
	fmt.Println(*user)

	instance2 := ReflectNew(25)
	i := instance2.(*int)
	fmt.Println(*i)
}

2. 通过反射方法reflect.Zero()设置空值

func TestReflectSetNil(t *testing.T){
	u := User{Name: "张三", Age:  15}
	value := reflect.ValueOf(&u).Elem()
	typ := reflect.TypeOf(&u).Elem()
	value.Set(reflect.Zero(typ))
	fmt.Println(u)
}

3.