当前位置:网站首页>Golang泛型的巧妙应用,防止变量空指针错误,防止结构体字段空指针错误
Golang泛型的巧妙应用,防止变量空指针错误,防止结构体字段空指针错误
2022-06-29 23:38:00 【Deng_Xian_Sheng】
//SafeValue
//可以传指针,也可以传值
//传指针则返回指针,传值则返回值
//遇到空指针会返回该类型的零值的指针
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
// 必须传入指针
// 它会将空指针的字段设置为该类型的零值的指针
// 传入空指针会返回一个所有字段都为零值的结构体
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()
}
边栏推荐
- Solr基础操作2
- 这个简单的小功能,半年为我们产研团队省下213个小时
- Pain points and solutions of M1 notebook home office | community essay solicitation
- 除子
- Cacti关于spine轮询的设置
- @Scheduled注解的坑,我替你踩了
- How to solve the problem that the computer time is not automatically updated after proofreading
- Under the epidemic, I left my job for a year, and my income increased 10 times
- Some of my favorite websites
- Implementation of aut, a self-developed transport layer protocol for sound network -- dev for dev column
猜你喜欢
Incluxdb time series database system
Open source the Ernie tiny lightweight technology of "Wenxin big model", which is accurate and fast, with full effect
海外数字身份验证服务商ADVANCE.AI入选EqualOcean《2022品牌出海服务市场研究报告》
这个简单的小功能,半年为我们产研团队省下213个小时
@Scheduled注解的坑,我替你踩了
Software testing interface testing postman testing tool interface testing process execution interface testing interface associated environment variables and global variables built-in dynamic parameter
Halcon实用:焊点检出设计思路
CE second operation
“微博评论”的高性能高可用计算架构
Head on Amway! Good looking and practical motor SolidWorks model material see here
随机推荐
Label Troubleshooting: unable to open the marked image
CE second operation
基金的利润分配与税收
flutter 插件版本冲突的解决方法
Project 1 - buffer pool [cmu 15-445645] notes
[leetcode] a number that appears only once [136]
招商证券靠谱吗?开股票账户安全吗?
Gracefully transform the SMS business module and start the strategic mode!
Head on Amway! Good looking and practical motor SolidWorks model material see here
绿树公司官方网站
PROJECT #1 - BUFFER POOL [CMU 15-445645]笔记
大厂试水 HPE推出Arm CPU通用服务器产品
sql刷题595. 大的国家
Why is JSX syntax so popular?
333333333333333333333333333333
按头安利 好看又实用的点胶机 SolidWorks模型素材看这里
自己收藏的一些网址
剑指 Offer 15. 二进制中1的个数
Leetcode(680)——验证回文字符串 Ⅱ
网上开户选哪个证券公司?还有,在线开户安全么?