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.

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

报告相同问题?

悬赏问题

  • ¥50 ZYNQ7020双核FLAHS烧写的问题
  • ¥20 ue 5 中想要实现第一人称人物左右行走摆动的效果,摄像头只向右摆动一次(关键词-结点)
  • ¥15 钢岔管添加弹性约束模拟围岩作用
  • ¥15 AD9164瞬时带宽1.8G,怎么计算出来?
  • ¥20 为什么安装CSiBridge时出现了这个问题,尝试了很多方法都不行,求详细操作步骤?
  • ¥15 鼠标右键,撤销删除 复制 移动,要怎样删除
  • ¥15 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题