当前位置:网站首页>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()
}
边栏推荐
- 按头安利!好看又实用的电机 SolidWorks模型素材看这里
- Node data collection and remote flooding transmission of label information
- Test d'installation du cluster metaq
- 大学里遗憾的事,希望你无怨也无悔
- AI赋能新零售,「智」胜之道在于生态思维|数智夜话直播精选摘录
- 网上开户选哪个证券公司?还有,在线开户安全么?
- constexpr 函数
- C指针进阶1-->字符指针,数组指针,指针与数组传参,函数指针
- Cacti最大监控数测试
- Status acquisition and control system of on-site express cabinet
猜你喜欢

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

二叉搜索树 230. 二叉搜索树中第K小的元素 1038. 从二叉搜索树到更大和树

Collection! Have you ever used these tools to improve programmer productivity?
![Project 1 - buffer pool [cmu 15-445645] notes](/img/33/304e3e78f62b156d0863a41d243679.png)
Project 1 - buffer pool [cmu 15-445645] notes

Why is JSX syntax so popular?

“微博评论”的高性能高可用计算架构

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

Regular expressions: characters (2)

matlab习题 —— 程序控制流程练习

Status acquisition and control system of on-site express cabinet
随机推荐
Leetcode(633)——平方数之和
Provide effective performance evaluation 
[leetcode] a number that appears only once [136]
LC:最大子数组和
Uniapp copy contents to clipboard
Node data collection and remote flooding transmission of label information
Constexpr function
Why is JSX syntax so popular?
数据库-玩转数据-Pgsql 使用UUID做主键
@Scheduled注解的坑,我替你踩了
RRDtool 画MRTG Log数据
Solr basic operation 1
Jetpack之Room的使用,结合Flow
成为唯一的key
High performance and high availability computing architecture of "microblog comments" in microblog system
C指针进阶1-->字符指针,数组指针,指针与数组传参,函数指针
動態代理的實現原理
打造一个 API 快速开发平台,牛逼!
基金的利润分配与税收
LC:有效的数独 + 旋转图像