1 回答
TA贡献1825条经验 获得超4个赞
你快到了。这是一些带有注释的工作代码:
var errBadArg = errors.New("must pass pointer to slice of pointer to struct")
func scanResults(dest interface{}) error {
resultsFromExternalSource := [][]interface{}{
{10, "user-name", float32(22)},
{20, "i-love-reflect", float32(100)},
}
// Get reflect.Value for the destination confirm that
// the destination is a pointer to a slice of pointers
// to a struct. The tests can be omitted if it's acceptable
// to panic on bad input argument.
destv := reflect.ValueOf(dest)
if destv.Kind() != reflect.Ptr {
return errBadArg
}
// Deference the pointer to get the slice.
destv = destv.Elem()
if destv.Kind() != reflect.Slice {
return errBadArg
}
elemt := destv.Type().Elem()
if elemt.Kind() != reflect.Ptr {
return errBadArg
}
// "deference" the element type to get the struct type.
elemt = elemt.Elem()
if elemt.Kind() != reflect.Struct {
return errBadArg
}
// For each row in the result set...
for j, row := range resultsFromExternalSource {
// Return error if more columns than fields in struct.
if len(row) > elemt.NumField() {
return errors.New("result larger than struct")
}
// Allocate a new slice element.
elemp := reflect.New(elemt)
// Dereference the pointer for field access.
elemv := elemp.Elem()
for i, col := range row {
fieldv := elemv.Field(i)
colv := reflect.ValueOf(col)
// Check to see if assignment to field will work
if !colv.Type().AssignableTo(fieldv.Type()) {
return fmt.Errorf("cannot assign %s to %s in row %d column %d", colv.Type(), fieldv.Type(), j, i)
}
// Set the field.
fieldv.Set(colv)
}
// Append element to the slice.
destv.Set(reflect.Append(destv, elemp))
}
return nil
}
- 1 回答
- 0 关注
- 151 浏览
添加回答
举报