lundi 19 juillet 2021

Assign a string to a struct via reflect

I have a struct, where I wish to dynamically change a string to another string using reflect. My issue is that the new string is created on the stack, and therefore the Set() method panics.

This makes sense to me, but I don't know how to fix it. I'm not sure the easy way to declare a string as addressable or if there's a different reflection technique to use.

type MyStruct struct {
    SomeField string
}

func main() {
    myStruct := MyStruct{"initial"}
    hello := "hello world"
    
    field := reflect.ValueOf(myStruct).FieldByName("SomeField")
    helloValue := reflect.ValueOf(hello)
    fmt.Printf("hello is on the stack, canAddr is %v\n", helloValue.CanAddr())
    
    // This will panic because canAddr is false
    field.Set(helloValue)
}

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





Aucun commentaire:

Enregistrer un commentaire