如何附加到空接口(已验证为 *[] 结构)?
func main() {
var mySlice []myStruct // myStruct can be any struct (dynamic)
decode(&mySlice, "...")
}
func decode(dest interface{}, src string) {
// assume dest has been verified to be *[]struct
var modelType reflect.Type = getStructType(dest)
rows, fields := getRows(src)
for _, row := range rows {
// create new struct of type modelType and assign all fields
model := reflect.New(modelType)
for field := fields {
fieldValue := getRowValue(row, field)
model.Elem().FieldByName(field).Set(fieldValue)
}
castedModelRow := model.Elem().Interface()
// append model to dest; how to do this?
// dest = append(dest, castedModelRow)
}
}
我尝试过的事情:
这只是 panic: reflect: call of reflect.Append on ptr Value (当我们传递 &mySlice 而不是 mySlice 时)
dest = reflect.Append(reflect.ValueOf(dest), reflect.ValueOf(castedModelRow))
这有效但不会将值设置回 dest... 在主函数中,调用解码函数后 len(mySlice) 保持为 0。
func decode(dest interface{}, src string) {
...
result := reflect.MakeSlice(reflect.SliceOf(modelType), rowCount, rowCount)
for _, row : range rows {
...
result = reflect.Append(result, reflect.ValueOf(castedModelRow))
}
dest = reflect.ValueOf(result)
繁花不似锦
相关分类