go - 范围变量的正确方法?
问题描述
我有一个不断扩展的 switch 语句中的代码。不过,我想把它变成一个循环。知道如何将其更改为循环,因为这通常是相同的代码?
switch key {
case types.CREATE_NEW_BUCKETS_INTERVAL_KEY:
b.OngoingCreateNewBucketsInterval.CorrelationID = correlationID //Notice how this is repeating
b.OngoingCreateNewBucketsInterval.Task = m[types.TASK]
b.OngoingCreateNewBucketsInterval.ExecuteTime = executeTime
case types.BUCKET_SWEEP_KEY:
b.OngoingBucketSweep.CorrelationID = correlationID
b.OngoingBucketSweep.Task = m[types.TASK]
b.OngoingBucketSweep.ExecuteTime = executeTime
case types.SEND_STATUS_ON_FINISHED_KEY:
b.OngoingSendStatusOnFished.CorrelationID = correlationID
b.OngoingSendStatusOnFished.Task = m[types.TASK]
b.OngoingSendStatusOnFished.ExecuteTime = executeTime
}
有没有办法只循环变量?
这些都是 ScheduledTask 类型,如下所示:
type ScheduleTask struct {
Task string `json:"task"`
ExecuteTime int64 `json:"execute_time"`
CorrelationID int64 `json:"correlation_id"`
}
解决方案
使用函数捆绑重复的逻辑:
set := func(t *ScheduleTask) {
t.CorrelationID = correlationID
t.Task = m[types.TASK]
t.ExecuteTime = executeTime
}
switch key {
case types.CREATE_NEW_BUCKETS_INTERVAL_KEY:
set(&b.OngoingCreateNewBucketsInterval)
case types.BUCKET_SWEEP_KEY:
set(&b.OngoingBucketSweep)
case types.SEND_STATUS_ON_FINISHED_KEY:
set(&b.OngoingSendStatusOnFished)
}
另一种选择是使用该指针获取指向计划任务和字段的指针:
var t *ScheduleTask
switch key {
case types.CREATE_NEW_BUCKETS_INTERVAL_KEY:
t = &b.OngoingCreateNewBucketsInterval
case types.BUCKET_SWEEP_KEY:
t = &b.OngoingBucketSweep
case types.SEND_STATUS_ON_FINISHED_KEY:
t = &b.OngoingSendStatusOnFished
}
t.CorrelationID = correlationID
t.Task = m[types.TASK]
t.ExecuteTime = executeTime
推荐阅读
- c - C 中管道、greps、wc 的堆栈粉碎问题
- matlab - 查找任意数量的向量的第一次出现
- javascript - 动态添加不同数组中的对象
- rust - 为什么生命周期规则有利于字符串文字?
- laravel - 如何防止两个 Laravel 中间件创建无休止的重定向?
- javascript - 如何使用 React Native 访问对象的属性?
- ruby-on-rails - 如何使用 Ruby on Rails 在特定时间自动生成一个类的新实例?
- kylin - 使用不区分大小写的用户名登录失败
- forms - 带有 rgb 颜色的 IE Edge 表单提交问题
- mongodb - 如何在 mongoDB 中按天/月分组?