mardi 23 avril 2019

Get pointer to float64 struct field from field name

I'm trying to write a function that returns a pointer to a struct field given the name of the field. Here's what I've currently got. It panics with the complaint reflect.Value.Addr of unaddressable value.

I assume I must be using reflect incorrectly in GetF64CtlAddr() but despite looking at related questions on SO as well reading the doc for reflect and The Laws of Reflection I'm stuck.

https://play.golang.org/p/cg5-wwiYcEv

package main

import (
    "fmt"
    "reflect"
)

type Ctl struct {
    Fval float64
}
// getCtlF64Addr is meant to return a pointer to a float64 Ctl struct field
// Note: err handling not yet implemented. 
func getCtlF64Addr(p *Ctl, field string) (f *float64, err error) {
    r := reflect.ValueOf(p)
    v := reflect.Indirect(r).FieldByName(field)
    x := v.Addr().Interface() // panics
    return x.(*float64), err
}

var State = Ctl{27}

func main() {
    p := &(State.Fval)
    fmt.Println(*p)                          // This succeeds, so State.Fval is addressable
    fp, err := getCtlF64Addr(&State, "fval") // but this panics
    if err != nil {
        fmt.Printf("%x", err)
    }
    fmt.Println(*fp)
}





Aucun commentaire:

Enregistrer un commentaire