Mainly i have bigger requirement:
type TestStruct struct {
  Slice []*TestItem
}

type TestItem struct {
  Value1 string
  Value2 string
}

so i need to create slice via reflect in TestStruct variable, create
variable for TestItem and iterate over TestItem fields and assign to
it Value1 and Value2 some text

after some changes i have reflect: call of reflect.Value.NumField on ptr Value
so reflect.New(sfield.Type.Elem()).Elem() returns pointer to needed
struct, but if i'm use reflect.Indirect i have nil variable and can't
do NumField on it

пн, 9 дек. 2019 г. в 12:30, Vasiliy Tolstov <v.tols...@selfip.ru>:

>
> Hi! I'm stuck at reflection based struct assignment.
>
> example struct
> type TestStruct struct {
>   Slice []*string
> }
>
> func TestReflect(t *testing.T) {
>   s1 := "one"
>   s2 := "two"
> s1 := "one"
> s2 := "two"
> nodes := []*string{&s1, &s2}
> v := &TestStruct{}
> valueOf := reflectValue(v)
> typeOf := reflectType(v)
>
> for i := 0; i < valueOf.NumField(); i++ {
>   field := valueOf.Field(i)
>   sfield := typeOf.Field(i)
>
>   slice := reflect.MakeSlice(sfield.Type, 0, 0)
>
>   log.Printf("field %v\n", field)
>   log.Printf("sfield %v\n", sfield)
>   log.Printf("slice %v\n", slice)
>
>   for _, node := range nodes {
>     log.Printf("sfield elem %v\n", sfield.Type.Elem())
>     value := reflect.New(sfield.Type.Elem())
>     setVal := reflect.ValueOf(node)
>     log.Printf("value %v\n", value)
>     value.Set(setVal)
>   }
> }
>
> but i'm have error
> panic: reflect: reflect.flag.mustBeAssignable using unaddressable
> value [recovered]
>         panic: reflect: reflect.flag.mustBeAssignable using unaddressable 
> value
>
>
> --
> Vasiliy Tolstov,
> e-mail: v.tols...@selfip.ru



--
Vasiliy Tolstov,
e-mail: v.tols...@selfip.ru

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CACaajQsKQx4PfYqga8vtyKpKXKVMTR3y3Zt9VReD4Op9nsFmoQ%40mail.gmail.com.

Reply via email to