1 回答

TA貢獻1869條經驗 獲得超4個贊
為了Assign工作,第二個參數必須是可尋址的,即您需要傳遞一個指向結構值的指針。
// the second argument MUST be a pointer to the struct
Assing(source, &target)
然后您需要稍微修改您的實現,Assign因為指針沒有文件。您可以使用該Elem()方法獲取指針指向的結構體值。
func Assign(sour interface{}, dist interface{}) uint {
counter := 0
source := reflect.ValueOf(sour)
// dist is expected to be a pointer, so use Elem() to
// get the type of the value to which the pointer points
target := reflect.ValueOf(dist).Elem()
typeSource := reflect.TypeOf(sour)
typeTarget := target.Type()
for i := 0; i < source.NumField(); i++ {
for j := 0; j < target.NumField(); j++ {
if typeSource.Field(i).Type == typeTarget.Field(j).Type && typeSource.Field(i).Name == typeTarget.Field(j).Name {
counter = counter + 1
target.FieldByName(typeSource.Field(i).Name).Set(source.Field(i))
}
}
}
return uint(counter)
}
- 1 回答
- 0 關注
- 145 瀏覽
添加回答
舉報