2016-07-16 115 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