mardi 8 janvier 2019

Initialize field with zero value using reflection

Is it possible to initialize variable with zero value via reflection?

I have code:

type Struct struct {
    v int
}

func ZeroStructInit() (r *Struct) {
    m := reflect.ValueOf(r).Elem()
    el := reflect.New(m.Type())
    m.Set(el)
    return r
}

func main() {
    log.Printf("%v", ZeroStructInit())
}

This code panicked with:

Panic: reflect: call of reflect.Value.Type on zero Value





Aucun commentaire:

Enregistrer un commentaire