0
我有下面的结构设置一个指向一个领域,需要一些字段是nulluble,所以我使用指针,主要是为了处理SQL空使用反射
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))
但是当我尝试做这一切使用反射
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