当前位置:网站首页>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()
}
边栏推荐
- SQL question brushing 595 Big country
- FPGA开发(1)——串口通信
- Open source the Ernie tiny lightweight technology of "Wenxin big model", which is accurate and fast, with full effect
- 二叉搜索树 230. 二叉搜索树中第K小的元素 1038. 从二叉搜索树到更大和树
- InfluxDB时序数据库系统
- Cacti最大监控数测试
- 声网自研传输层协议 AUT 的落地实践丨Dev for Dev 专栏
- Halcon实用:焊点检出设计思路
- [leetcode] a number that appears only once [136]
- CE second operation
猜你喜欢

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

海外数字身份验证服务商ADVANCE.AI入选EqualOcean《2022品牌出海服务市场研究报告》

剑指 Offer 15. 二进制中1的个数
![[译]在软件开发行业工作 6 年后,那些年我曾改过的观念](/img/69/c9829b14223f1e8fd3137d0750d8f7.png)
[译]在软件开发行业工作 6 年后,那些年我曾改过的观念

剑指 Offer 14- II. 剪绳子 II

After working in the software development industry for six years, I changed my ideas in those years

Speech signal processing (II): phonation physiology, auditory physiology and auditory psychology

Overseas digital authentication service provider advance AI was selected into the "2022 brand sea Service Market Research Report" of equalocean

Why is JSX syntax so popular?

开始“收割”!钉钉调整“钉钉Teambition”免费用人数上限,超十人将无法正常用
随机推荐
Uniapp copy contents to clipboard
333333333333333333333333333333
LC:有效的数独 + 旋转图像
[LeetCode] 只出现一次的数字【136】
2022 PMP project management examination agile knowledge points (5)
LC:最大子数组和
Solr basic operation
Head on Amway! Good looking and practical motor SolidWorks model material see here
xutils3传集合
Dépannage de l'étiquette: impossible d'ouvrir l'image marquée
剑指 Offer 14- I. 剪绳子
收藏!这些提高程序员生产力的工具你用过吗?
InfluxDB时序数据库系统
剑指 Offer 14- II. 剪绳子 II
招商证券靠谱吗?开股票账户安全吗?
Database - playful data -pgsql uses UUID as primary key
二叉树的序列化 力扣 297. 二叉树的序列化与反序列化 652. 寻找重复的子树
Principe de réalisation de l'agent dynamique
matplotlib matplotlib可视化之柱状图plt.bar()
@Scheduled annotation pit, I stepped on it for you