2 回答

TA贡献1843条经验 获得超7个赞
问题出reflect.Zero在我创建 slie 的reflect.New时候。在这里,您有完整的工作示例。
https://play.golang.org/p/3mIEFqMxk-
package main
import (
"encoding/json"
"fmt"
"reflect"
)
type A struct {
Name string `column:"email"`
}
func main() {
bbb(&A{})
}
func aaa(v interface{}) {
t := reflect.TypeOf(v)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() == reflect.Slice {
t = t.Elem()
} else {
panic("Input param is not a slice")
}
sl := reflect.ValueOf(v)
if t.Kind() == reflect.Ptr {
sl = sl.Elem()
}
st := sl.Type()
fmt.Printf("Slice Type %s:\n", st)
sliceType := st.Elem()
if sliceType.Kind() == reflect.Ptr {
sliceType = sliceType.Elem()
}
fmt.Printf("Slice Elem Type %v:\n", sliceType)
for i := 0; i < 5; i++ {
newitem := reflect.New(sliceType)
newitem.Elem().FieldByName("Name").SetString(fmt.Sprintf("Grzes %d", i))
s := newitem.Elem()
for i := 0; i < s.NumField(); i++ {
col := s.Type().Field(i).Tag.Get("column")
fmt.Println(col, s.Field(i).Addr().Interface())
}
sl.Set(reflect.Append(sl, newitem))
}
}
func bbb(v interface{}) {
t := reflect.TypeOf(v)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
panic("Input param is not a struct")
}
models := reflect.New(reflect.SliceOf(reflect.TypeOf(v))).Interface()
aaa(models)
fmt.Println(models)
b, err := json.Marshal(models)
if err != nil {
panic(err)
}
fmt.Println(string(b))
}

TA贡献1801条经验 获得超16个赞
这是做你想做的吗?(游乐场链接)
package main
import (
"fmt"
"reflect"
)
type A struct{ Name string }
func main() {
bbb(A{})
}
func aaa(v interface{}) interface{} {
sl := reflect.Indirect(reflect.ValueOf(v))
typeOfT := sl.Type().Elem()
ptr := reflect.New(typeOfT).Interface()
s := reflect.ValueOf(ptr).Elem()
return reflect.Append(sl, s)
}
func bbb(v interface{}) {
myType := reflect.TypeOf(v)
models := reflect.MakeSlice(reflect.SliceOf(myType), 0, 1).Interface()
fmt.Println(aaa(models))
}
请注意,我正在返回新切片。我认为您需要另一层间接(指向指针的指针)才能在没有返回值的情况下执行此操作,但这是我第一次在 Go 中进行反射,所以我可能会做错事。
- 2 回答
- 0 关注
- 223 浏览
添加回答
举报