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
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭