doww38701 2016-11-09 17:03
浏览 117
已采纳

Golang:将接口转换回其原始类型

I couldn't really find an answer to this, even though I looked up the Go documentation and examples. Is it possible to cast an interface back to its original type, dynamically? I know I can do something like this:

var myint int = 5
var myinterface interface{}
myinterface = myint
recovered, _ := myinterface.(int)
fmt.Println(recovered)

But here I know the type. I would like to have a map of unknown types (interfaces) and cast them back by using reflection, like this:

// put/pop writes/read to/from a map[string]interface{}
var myint int = 5
put("key" myint)
pop("key", &myint) // this should also work for objects or any other type

Like this it would by possible to store anything within a single map. The type will be handed in by the user when calling pop() (second argument is an interface). Is it possible to achive this using reflection?

  • 写回答

1条回答 默认 最新

  • dongtong2021 2016-11-09 17:18
    关注

    You can't assert a type from an interface without knowing what that type is at compile time, but you can set a value from an interface via reflection. Here's an example without any error checks, which panics when any parameters don't match:

    var m = map[string]interface{}{}
    
    func put(k string, v interface{}) {
        m[k] = v
    }
    
    func pop(k string, o interface{}) {
        reflect.ValueOf(o).Elem().Set(reflect.ValueOf(m[k]))
    }
    

    https://play.golang.org/p/ORcKhtU_3O

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

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?