dongmu3187 2017-09-20 05:59 采纳率: 0%
浏览 90
已采纳

从golang中的特定接口获取基础类型

As the example, can I get a zero value of its underlying type from the interface Work?

func MakeSomething(w Worker){
    w.Work()

    //can I get a zeor value type of The type underlying w?
    //I tried as followed, but failed

    copy :=w
    v := reflect.ValueOf(&copy)
    fm :=v.Elem()
    modified :=reflect.Zero(fm.Type())//fm.type is Worker, and modified comes to be nil
    fm.Set(modified)
    fmt.Println(copy)
}

type Worker interface {
    Work()
}

the playground

  • 写回答

1条回答 默认 最新

  • doujiao7679 2017-09-20 06:33
    关注

    Since w contains a pointer to a Worker, you might want to get a zero value of the element it is pointing to. Once you get the element, you can create a zero value of its type:

    v := reflect.ValueOf(w).Elem() // Get the element pointed to
    zero := reflect.Zero(v.Type()) // Create the zero value
    

    Above code snippet will panic if you pass in a non-pointer to MakeSomething. To prevent this, you might want to do the following instead:

    v := reflect.ValueOf(w)
    if reflect.TypeOf(w).Kind() == reflect.Ptr {
        v = v.Elem()
    }
    zero := reflect.Zero(v.Type())
    

    If you actually want to have a pointer to a new Worker, you just replace reflect.Zero(v.Type()) with reflect.New(v.Type()).

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器