2011-07-05 4 views
1

저는 Go가 매우 새롭습니다. Reflection in Go를 사용하여 어떻게 매핑의 가치를 얻는 지 궁금합니다.골란이 반영을 통해 가치를 얻습니다.

 

type url_mappings struct{ 
    mappings map[string]string 
} 

func init() { 
    var url url_mappings 
    url.mappings = map[string]string{ 
     "url": "/", 
     "controller": "hello"} 
 

감사

+1

왜 리플렉션을 사용 하시겠습니까? 어떤 문제를 해결하려고합니까? – peterSO

+0

나는 사용자가 자신의 맵핑을 갖도록하려고 노력하고 있으며, 리플렉션을 사용하여 루프를 통해 모든 패턴을 점검합니다. Grails의 URL_Mappings과 같습니다. :) – toy

+0

@toy : 왜 반사가 필요한지 아직도 이해할 수 없다. – newacct

답변

5
import "reflect" 
v := reflect.ValueOf(url) 
f0 := v.Field(0) // Can be replaced with v.FieldByName("mappings") 
mappings := f0.Interface() 

mappings의 유형은 인터페이스 {}, 그래서 당신은 맵으로 사용할 수 없습니다. 이 종류인지 실제 mappings을 위해 사용해야합니다, map[string]string 일부 type assertion :

realMappings := mappings.(map[string]string) 
println(realMappings["url"]) 
때문에 반복 map[string]string

, I 것 : 다음

type mappings map[string]string 

그리고 당신 할 수 있습니다 :

type url_mappings struct{ 
    mappings // Same as: mappings mappings 
} 
+0

이걸 실행할 때이 오류가 발생했습니다. – toy

+0

testing : panic : reflect : call ofref.Value · ptr 값 필드 – toy

+2

그 이유는'url' 대신에'url'에 대한 포인터를 넘기 때문입니다. 만약 당신이 포인터를 넘겨 주길 원한다면 * line 2 *를'v : = reflect.ValueOf (url) .Elem()'으로 바꾼다. –

관련 문제