2017-02-17 2 views
2

나는 이름, 종류와에 전달되는 임의의 구조체의 모든 필드의 유형을 나열합니다 루틴을 구축하는 반사를 사용하기 위해 노력하고있어 여기에 지금까지있어 무엇 :Golang Reflection을 사용하여 슬라이스 인 구조체 필드의 유형을 얻는 방법? .

type StatusVal int 
type Foo struct { 
    Name string 
    Age int 
} 
type Bar struct { 
    Status StatusVal 
    FSlice []Foo 
} 

func ListFields(a interface{}) { 
    v := reflect.ValueOf(a).Elem() 
    for j := 0; j < v.NumField(); j++ { 
     f := v.Field(j) 
     n := v.Type().Field(j).Name 
     t := f.Type().Name() 
     fmt.Printf("Name: %s Kind: %s Type: %s\n", n, f.Kind(), t) 
    } 
} 

func main() { 
    var x Bar 
    ListFields(&x) 
} 

출력은 다음 :

필드 슬라이스가
Name: Status Kind: int Type: StatusVal 
Name: FSlice Kind: slice Type: 

는 종류가 비어. 나는 슬라이스의 데이터 형식을 액세스 할 수있는 몇 가지 방법을 시도하지만, 모든 시도는 ... 공황의 결과 보통이 하나 변경이 코드에 할 필요가있는 무엇

reflect: call of reflect.Value.Elem on slice Value 

있도록 포함한 모든 필드에 대한 입력 슬라이스가 출력에 나열됩니까? https://play.golang.org/p/zpfrYkwvlZ

답변

2

[]Foo 같은 리터럴 유형에 주어진 슬라이스 타입이 때문에 Type.Name() 빈 문자열 ""을 반환 이름이 유형 :

여기 놀이터 링크입니다. 대신

사용 Type.String() :

t := f.Type().String() 

그리고 출력합니다 (Go Playground에 그것을 시도) : Identify non builtin-types using reflect

+0

:

Name: Status Kind: int Type: main.StatusVal Name: FSlice Kind: slice Type: []main.Foo 

이 관련 질문 유형과 이름에 대한 자세한 내용을 알고보기

아름다운! 감사합니다 icza! – sman

관련 문제