我试图用指针构造 Book 结构的切片,但我无法通过 Go 中的反射使其工作。
[]*Book 结构指针的 Book 切片,请注意,scanResults 方法可能会接收任何类型的切片,而不仅仅是 Book 结构。所以我希望在运行时动态构建一个切片
你能告诉我我在下面的代码片段中出错了吗?
package main
import (
"reflect"
"errors"
"fmt"
)
type Book struct {
Id int
Title string
Price float32
}
func main() {
var dest []*Book
scanResults(&dest)
}
func scanResults(dest interface{}) error{
resultsFromExternalSource := []interface{}{10 , "user-name" , float32(22)}
value := reflect.ValueOf(dest)
if value.Kind() != reflect.Ptr {
return errors.New("must pass a pointer, not a value, to scan results into struct destination")
}
sliceElement := reflect.TypeOf(dest).Elem()
if sliceElement.Kind() != reflect.Slice {
return fmt.Errorf("expected %s but got %s", reflect.Slice, sliceElement.Kind())
}
structPtr := sliceElement.Elem()
if structPtr.Kind() != reflect.Ptr {
return fmt.Errorf("expected %s but got %s", reflect.Ptr, structPtr.Kind())
}
structElemType := reflect.TypeOf(structPtr).Elem()
if structElemType.Kind() != reflect.Struct {
return fmt.Errorf("expected %s but got %s", reflect.Struct, structElemType.Kind())
}
structRecordInterface := reflect.New(structElemType).Elem().Interface() // create a new struct
structRecordType := reflect.TypeOf(structRecordInterface)
structRecordValue := reflect.ValueOf(structRecordType)
for i, result := range resultsFromExternalSource {
if structRecordValue.Field(i).CanSet() {
structRecordValue.Field(i).Set(reflect.ValueOf(result))
} else {
varName := structRecordType.Field(i).Name
varType := structRecordType.Field(i).Type
return fmt.Errorf("cannot scan results into passed struct destination as the struct field %v with %v type is not settable", varName, varType)
}
}
return nil
}
https://play.golang.org/p/O9j4RobQqMy
凤凰求蛊
相关分类