首页 > 解决方案 > 范围变量的正确方法?

问题描述

我有一个不断扩展的 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"`
}

标签: go

解决方案


使用函数捆绑重复的逻辑:

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

推荐阅读