dongmu3187
dongmu3187
采纳率0%
2017-09-20 05:59 阅读 70
已采纳

从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 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()).

    点赞 评论 复制链接分享

相关推荐