当前位置:网站首页>Go learning --- use reflection to judge whether the value is valid

Go learning --- use reflection to judge whether the value is valid

2022-07-06 07:11:00 Duck boss

One 、 Use reflection to determine whether the value is valid

package main

import (
	"fmt"
	"reflect"
)
// Define a structure 
type Tom struct {

}
func main() {
	var a *int
	isNilA := reflect.ValueOf(a).IsNil()
	fmt.Println(" Determine whether the pointer is initialized :",isNilA)
	var b *int = new(int)
	isNilB := reflect.ValueOf(b).IsNil()
	fmt.Println(" Determine whether the pointer is initialized :",isNilB)
	var c int
	zero := reflect.ValueOf(c).IsZero()
	fmt.Println("c Whether the value of is zero :",zero)
	c = 1
	zeros := reflect.ValueOf(c).IsZero()
	fmt.Println("c Whether the value of is zero :",zeros)
	var d int
	// To see if it works 
	valid := reflect.ValueOf(d).IsValid()
	fmt.Println("d Whether it works :",valid)
	d = 2
	fmt.Println("d Whether it works :",reflect.ValueOf(d).IsValid())
	tom := Tom{}
	fmt.Println(" Whether the internal attribute name of the structure is valid ",reflect.ValueOf(tom).FieldByName("name").IsValid())
	fmt.Println(" Whether the structure method is effective :",reflect.ValueOf(tom).MethodByName("name").IsValid())
	m := make(map[interface{}]interface{})
	fmt.Println(reflect.ValueOf(m).MapIndex(reflect.ValueOf(3)).IsValid())
}

 

原网站

版权声明
本文为[Duck boss]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131935507461.html