douna1895 2016-02-26 17:44
浏览 94
已采纳

指向循环变量的指针,用于遍历接口或地图切片的范围{}

I'm using go-hdf5 and I'm hitting a problem when trying to write attributes in a loop from a map.

The attributes are created correctly (correct name and datatype) but the written value is garbage.

The same code outside of the loop works fine. I tried both the v := v idiom and wrapping the code in a closure to capture v but it doesn't make a difference.

Here is the gist of the code (error checking intentionally left out for clarity):

m := map[string]interface{"foo", 42}
for k, v := range m {
    // [...]
    v := v
    attr.Write(&v, dtype)
}

The Write method is using reflection to grab a pointer to the value and forwards it to the C library. The relevant part of the code is just:

func (s *Attribute) Write(data interface{}, dtype *Datatype) error {
    v := reflect.ValueOf(data)
    addr := unsafe.Pointer(v.Pointer())
    return h5err(C.H5Awrite(s.id, dtype.id, addr))
}

If I replace the map by a slice of interface{}, I get the exact same problem so my hunch is that this has to do with the binding of loop variables, but yet v := v doesn't help so I'm not sure.

I'm quite familiar with Go, HDF5 (C library) and go-hdf5 but I'm really stuck here. Any idea?

BTW I'm using go1.5.1 darwin/amd64.

  • 写回答

1条回答 默认 最新

  • doudi2005 2016-02-26 19:47
    关注

    The Write method needs a pointer to a value, not a pointer to an interface containing the value. You can get it using reflection:

    u := reflect.New(reflect.ValueOf(v).Type())
    u.Elem().Set(reflect.ValueOf(v))
    v := u.Interface()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料