samedi 7 mars 2020

Check if underlying type is a struct with reflect

Given this struct

type A struct {
  b *B
  c string
  d string
}

I want to check with reflect which fields have a struct behind the pointer type, so specifically I want to create a condition that would only be true when iterating over field b. From what I've tried using the reflect documentation I always end up with an invalid Value kind which doesn't allow me to go further as every subsequent method panics.

package main

import (
    "fmt"
    "reflect"
)

type A struct {
  b *B
  c string
  d string
}

type B struct {
}

func main() {
        val := reflect.ValueOf(A{})
    for i := 0; i < val.Type().NumField(); i++ {
        if val.Field(i).Kind() == reflect.Ptr {
            fmt.Println(reflect.Indirect(val.Field(i)).Kind())
        }
        fmt.Println(val.Field(i).Kind())
    }
}

https://play.golang.org/p/oRry3ZubRxI





Aucun commentaire:

Enregistrer un commentaire