mardi 16 juillet 2019

How to set field of interface?

I have a slice []interface{} and there is struct value in it.

When I try to reflect the slice's element to update the struct's field. I got following error

panic: reflect: reflect.Value.SetInt using unaddressable value

Minimize code here:

https://play.golang.org/p/VOycEtG2Nq5

package main

import (
    "fmt"
    "reflect"
)

type A struct {
    B int
}

func main() {
    array := []interface{}{A{1}}
    v := reflect.ValueOf(&array)
    va := v.Elem().Index(0)
    fmt.Println(va.Kind() == reflect.Interface) // true
    fmt.Println(va.CanAddr()) // true
    f := va.Elem().Field(0)
    f.SetInt(2)
    fmt.Println(array)
}





Aucun commentaire:

Enregistrer un commentaire