2016-07-16 10 views
0

を探す:構造体のフィールドに再帰的に

var Foo struct { 
    Bar struct { 
     blah *bool 
    } 
} 

を私はパラメータとしてのインタフェースを取る関数に構造体を送信する、フィールドを見つけるためにリフレクションを使用する簡単な方法があります"blah"という名前でinVal.FieldByName("blah")を使用していますか?

答えて

1

は、ここでそれを行うための一つの方法です:

func findField(v interface{}, name string) reflect.Value { 
    // create queue of values to search. Start with the function arg. 
    queue := []reflect.Value{reflect.ValueOf(v)} 
    for len(queue) > 0 { 
    v := queue[0] 
    queue = queue[1:] 
    // dereference pointers 
    for v.Kind() == reflect.Ptr { 
     v = v.Elem() 
    } 
    // ignore if this is not a struct 
    if v.Kind() != reflect.Struct { 
     continue 
    } 
    // iterate through fields looking for match on name 
    t := v.Type() 
    for i := 0; i < v.NumField(); i++ { 
     if t.Field(i).Name == name { 
      // found it! 
      return v.Field(i) 
     } 
     // push field to queue 
     queue = append(queue, v.Field(i)) 
    } 
    } 
    return reflect.Value{} 
} 

playground example

+0

ありがとうございました!それは素晴らしい解決策です。 – TheOriginalAlex

関連する問題