mardi 8 septembre 2020

Using reflect to access struct field within a struct

I have the following:

package main

import (
    "fmt"
    "reflect"
)

type Model struct {
    A AStruct
}

type AStruct struct {
    ID string
}

type IModel interface {
}

func main() {
    m := Model{AStruct{ID:"123"}}
    var i IModel;
    i = m
    
    v := reflect.Indirect(reflect.ValueOf(m))
    for i := 0; i < v.NumField(); i++ {
        fieldVal := v.Field(i)
        fmt.Println("fieldVal.Kind():", fieldVal.Kind())
    }
    
    // How do I get it to work with FieldByName("ID") and print 123?
    
    fmt.Println("i is", i)
}

I want to use reflect to print "123" but I can't it to work.

The go playground





Aucun commentaire:

Enregistrer un commentaire