help with reflect

333 views
Skip to first unread message

Vasiliy Tolstov

unread,
Dec 9, 2019, 4:31:33 AM12/9/19
to golang-nuts
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.to...@selfip.ru

Vasiliy Tolstov

unread,
Dec 9, 2019, 5:17:42 AM12/9/19
to Vasiliy Tolstov, golang-nuts
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.to...@selfip.ru>:

Vasiliy Tolstov

unread,
Dec 9, 2019, 6:58:33 AM12/9/19
to Vasiliy Tolstov, golang-nuts
Nevermind. I found the error

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

Dan Kortschak

unread,
Dec 9, 2019, 4:50:04 PM12/9/19
to golang-nuts
On Mon, 2019-12-09 at 14:57 +0300, Vasiliy Tolstov wrote:
> Nevermind. I found the error

https://paulcunningham.me/nevermind-found-answer/

Vasiliy Tolstov

unread,
Dec 12, 2019, 5:50:31 AM12/12/19
to Dan Kortschak, golang-nuts
вт, 10 дек. 2019 г. в 00:49, Dan Kortschak <d...@kortschak.io>:
>
> On Mon, 2019-12-09 at 14:57 +0300, Vasiliy Tolstov wrote:
> > Nevermind. I found the error
>
> https://paulcunningham.me/nevermind-found-answer/
>

Ok, sorry, i'm try to provide answer for next time =)
Reply all
Reply to author
Forward
0 new messages