반사

2014-07-22 3 views
0

내가 가지고있는 다음과 같은 구조체를 사용하여 필드에 대한 포인터를 설정하고 그래서 내가 주로 SQL 널 (null)반사

을 처리하기 위해, 포인터를 사용 nulluble로 일부 필드가 필요
type Chicken struct{ 
    Id    int   //Not nullable 
    Name    *string  //can be null 
    AvgMonthlyEggs *float32 //can be null 
    BirthDate   *time.Time //can be null 
} 

그래서 난 다음 내가 할 때 json으로 결과가 내가

stringValue:="xx" 
chicken := &Chicken{1,&stringValue,nil,nil} 
chickenJson,_ := json.Marshal(&chicken) 
fmt.Println(string(chickenJson)) 

을 원하는되는 값 유형에 대해 널 (null)을 가질 수 있음을 볼 수 있지만, 나는 그것을 모두 사용하여 반사를 할 때

var chickenPtr *Chicken 
    itemTyp := reflect.TypeOf(chickenPtr).Elem() 
    item := reflect.New(itemTyp) 
    item.Elem().FieldByName("Id").SetInt(1) 
    //the problem is here not sure how to set the pointer to the field 
    item.Elem().FieldByName("Name").Set(&stringValue) //Error caused by this line 
    itemJson,_ := json.Marshal(item.Interface()) 
    fmt.Println(string(itemJson)) 
내가 반사 부에서 무엇을 얻을

다음과 같은 오류 내가 잘못하고있는 무슨

cannot use &stringValue (type *string) as type reflect.Value in argument to item.Elem().FieldByName("Name").Set 

입니까?

여기 GoPlay http://play.golang.org/p/0xt45uHoUn

답변