douzhang1364 2018-04-26 19:21 采纳率: 0%
浏览 36
已采纳

切片和指针的范围

I have the following range over a slice of a specific struct:

var t1, t2 *time.Time
for _, d := range entries {
    if d.EntryType == print {
        t1 = &d.LogTime
    }
    if d.EntryType == saw {
        t2 = &d.LogTime
    }
}

In my example I have two objects in my struct and I know that they are different. But when I Println both Time pointers with String or when I make some calculations, I can see that both have the same value of the second one.

When I change the assignment to

tmp := d.LogTime
t1 = &tmp

i can make my calculations, because both pointers are pointing to different objects.

  • 写回答

1条回答 默认 最新

  • dongwei3712 2018-04-26 19:25
    关注

    The application is taking the address of the variable d, not the address of a slice element. The variable d is scoped outside the loop and has the same address on each iteration of the loop.

    The code

    tmp := d.LogTime
    t1 = &tmp
    

    works because tmp is scoped inside the loop.

    Perhaps you intended to take the address of the slice element. If so, use this code:

    for i:= range entries {
        if d.EntryType == print {
            t1 = &entries[i].LogTime
        }
        if d.EntryType == saw {
            t2 = &entries[i].LogTime
        }
    }
    

    There may be a reason to use *time.Time values here, but typically applications work with time.Time. This code may do what you need:

    var t1, t2 time.Time
    for _, d := range entries {
        if d.EntryType == print {
            t1 = d.LogTime
        }
        if d.EntryType == saw {
            t2 = d.LogTime
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符