douren8379 2018-07-17 10:25
浏览 391
已采纳

如何将interface {}转换为结构指针?

Interfaces already contain a pointer to a value, and I in my case it's a struct, and I need to get a struct pointer out of an interface{}.

The use case is with sync.Map, where I put a struct containing a lock into the map, and with the Load() method I can read an interface{} value. I want to get the pointer to the original struct, so I don't copy the lock.

The alternative is to add a pointer to the struct to the Map instead, then read it back and cast the interface{} to the struct pointer, but I'm curious if the first case can be achieved.

  • 写回答

1条回答 默认 最新

  • douying9296 2018-07-17 11:31
    关注

    You can't do that. If you "wrap" a non-pointer value in an interface, you can only get a non-pointer value out of it, using either a type assertion or a type switch. And since type assertion expressions are not addressable, you can't get the address of the "value" wrapped in the interface.

    If you only have a value wrapped in an interface, you won't be able to get a pointer to the original value that was wrapped in the interface. Why? Because the value wrapped in the interface may only be a copy, completely detached from the original. See examples and explanation here: How can a slice contain itself?

    Note that under the hood the value actually wrapped may or may not be a pointer (depending on the value's size) even if you wrapped a non-pointer value, but this is implementation detail and is hidden from you. When you extract the value, you will of course get a non-pointer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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