当前位置:网站首页>Ingenious application of golang generics to prevent null pointer errors of variables and structural fields
Ingenious application of golang generics to prevent null pointer errors of variables and structural fields
2022-06-29 23:43:00 【Deng_ Xian_ Sheng】
//SafeValue
// Can pass pointer , You can also pass values
// Pass the pointer and return the pointer , Return value if value is passed
// A null pointer will return a pointer with a zero value of this type
func SafeValue[T any](v T) T {
vt := reflect.TypeOf(v)
switch vt.Kind() {
case reflect.Ptr:
vv := reflect.ValueOf(v)
if vv.IsNil() {
return reflect.New(vt.Elem()).Interface().(T)
}
return v
default:
return v
}
}
// SafeStruct
// Pointer must be passed in
// It will set the field of null pointer to the pointer of zero value of this type
// Passing in a null pointer returns a structure with zero values for all fields
func SafeStruct(v interface{
}) interface{
} {
vt := reflect.TypeOf(v)
vv := reflect.ValueOf(v)
if vv.IsNil() {
vv = reflect.ValueOf(reflect.New(vt.Elem()).Interface()).Elem()
} else {
vv = vv.Elem()
}
for i := 0; i < vv.NumField(); i++ {
if vv.Field(i).Kind() == reflect.Ptr && vv.Field(i).IsNil() {
vv.Field(i).Set(reflect.New(vv.Field(i).Type().Elem()))
}
}
return vv.Interface()
}
边栏推荐
猜你喜欢

Constexpr function

High performance and high availability computing architecture of "microblog comments" in microblog system

LC:最大子数组和

C pointer advanced 2-- > function pointer array callback function simplifies calculator code, and implements qsort function based on callback function simulation

Collection! Have you ever used these tools to improve programmer productivity?

Create an API rapid development platform, awesome!

云和恩墨盖国强,识别它、抓住它,在国产数据库沸腾以前

matplotlib matplotlib可视化之柱状图plt.bar()

收藏!这些提高程序员生产力的工具你用过吗?

333333333333333333333333333333
随机推荐
CE第二次作业
软件测试 接口测试 Jmeter 5.5 安装教程
What is online account opening? In addition, is it safe to open a mobile account?
均值、方差、标准差、协方差的概念及意义
The concept and significance of mean, variance, standard deviation and covariance
Sword finger offer 15 Number of 1 in binary
Provide effective performance evaluation 
Matplotlib plt Hist() parameter explanation
Start harvesting! Nailing: adjust the maximum number of free users of "nailing team". If the number exceeds 10, it will not work normally
Matplotlib histogram of Matplotlib visualization plt bar()
Head pressing Amway good-looking and practical dispensing machine SolidWorks model material here
M1笔记本居家办公的痛点及解决方案 | 社区征文
Overseas digital authentication service provider advance AI was selected into the "2022 brand sea Service Market Research Report" of equalocean
剑指 Offer 14- I. 剪绳子
MetaQ集群安装测试
Implementation principle of dynamic agent
High performance and high availability computing architecture of "Weibo comments"
机器学习:VC维的概念和用途
声网自研传输层协议 AUT 的落地实践丨Dev for Dev 专栏
关于二叉树