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

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

报告相同问题?