2 回答

TA貢獻1843條經驗 獲得超7個贊
問題出reflect.Zero在我創(chuàng)建 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))
}
請注意,我正在返回新切片。我認為您需要另一層間接(指向指針的指針)才能在沒有返回值的情況下執(zhí)行此操作,但這是我第一次在 Go 中進行反射,所以我可能會做錯事。
- 2 回答
- 0 關注
- 245 瀏覽
添加回答
舉報