当前位置:网站首页>golang interface “坑记录“
golang interface “坑记录“
2022-08-09 10:51:00 【ase2014】
问题
最近使用golang写一个分布式任务系统,需要将过程中的变量存储到数据库,以用于任务执行过程中,进程挂了,调度到另一个实例上去, 过程中的变量需要被存储。该变量的获取存在两种场景:直接从内存中获取,任务被重新调度,需要从数据库里获取,在内存中使用interface获取发现获取不到的现象,具体如下面示例代码的GetB,解决办法是内存通过type实现,或者reflect实现,如果存储到数据库的使用json marshal unmarshal即可
示例代码
func main() {
data := new(BT)
GetB(data)
fmt.Println("GetB ", data)
GetB1(data)
fmt.Println("GetB1 ", data)
data = new(BT)
GetB2(data)
fmt.Println("GetB2 ", data)
}
var b = &BT{
A: 1,
}
type BT struct {
A int
}
// 直接传入指针发现,返回的是空
func GetB(r interface{}) {
r = b
}
// 通过marshal和unmarshal获取发现可以
func GetB1(r interface{}) {
tmp, err := json.Marshal(b)
if err != nil {
fmt.Println("marshal failed, ", err.Error())
return
}
if json.Unmarshal(tmp, r) != nil {
fmt.Println("unmarshal failed, ", err.Error())
return
}
}
// 通过reflect的set value发现可以
func GetB2(r interface{}) {
rv := reflect.ValueOf(r)
bv := reflect.ValueOf(b)
if rv.Kind() == bv.Kind() {
rv.Elem().Set(bv.Elem())
}
}
边栏推荐
- Unix Environment Programming Chapter 15 15.3 Functions popen and pclose
- PoseNet: A Convolutional Network for Real-Time 6-DOF Camera Relocalization Paper Reading
- 1007 Maximum Subsequence Sum (25分)
- linux mysql操作的相关命令
- MATLAB代码实现三次样条插值
- 如何在gazebo进行 joint的转动控制
- pip common commands and changing source files
- unix环境编程 第十五章 15.7消息队列
- 在webgis中显示矢量化后的风险防控信息
- threejs+shader 曲线点运动,飞线运动
猜你喜欢
Dialogue with the DPO of a multinational consumer brand: How to start with data security compliance?See you on 8.11 Live!
[Error record] Solve the problem that ASRock J3455-ITX cannot be turned on without a monitor plugged in
985毕业,工作3年,分享从阿里辞职到了国企的一路辛酸和经验
Getting Started with MNIST Machine Learning
The complete grammar of CSDN's markdown editor
性能测试(05)-表达式和业务关联-json关联
Since I use the HiFlow scene connector, I don't have to worry about becoming a "dropper" anymore
Shell script combat (2nd edition) / People's Posts and Telecommunications Press Script 2 Validate input: letters and numbers only
OneNote 教程,如何在 OneNote 中搜索和查找笔记?
可能95%的人还在犯的PyTorch错误
随机推荐
人物 | 从程序员到架构师,我是如何快速成长的?
从位图到布隆过滤器
数据存储:对dataframe类,使用to_csv()将中文数据写入csv文件
pytorch widedeep文档
unix环境编程 第十五章 15.9 共享存储
UNIX Environment Programming Chapter 15 15.6 XSI IPC
verbose np.matmul/np.dot/np.multiply/tf.matmul/tf.multiply/*
Unix System Programming Chapter 15 15.2 Pipes
unix环境编程 第十五章 15.7消息队列
微信小程序——天气查询
activemq message persistence
MySQL查询性能优化七种武器之索引潜水
1005 Spell It Right (20分)
支付宝小程序的接入
机器学习-逻辑回归(logistics regression)
shell脚本实战(第2版)/人民邮电出版社 脚本2 验证输入:仅限字母和数字
性能测试(06)-逻辑控制器
研发需求的验收标准应该怎么写? | 敏捷实践
Unix Environment Programming Chapter 14 14.4 I/O Multiplexing
多商户商城系统功能拆解26讲-平台端分销设置