lin van
lin van

Reputation: 33

get underlying type from a specific interface in 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

Upvotes: 3

Views: 10133

Answers (1)

ANisus
ANisus

Reputation: 77925

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

Upvotes: 3

Related Questions