0

I'm having a bit of trouble setting a reflect.Value which is a string to something different.

In the follow GetValue() return a reflect.Value

val, err := exp.GetFact(t.(*api.Event_Set).Set.Key).GetValue()
if err != nil {
    ref := reflect.Indirect(val)
    ref.SetString(t.(*api.Event_Set).Set.Value)
}

Upon hitting SetString it throws a panic:

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

I've attempted different syntax ie without an Indirect, with an Elem() etc. How do I correctly change the value of the string?

10
  • 1
    What is the type of val? Commented Apr 23, 2021 at 21:21
  • Oh yeah, I mentioned above GetValue returns reflect.Value. The value contained is a basic string. Commented Apr 23, 2021 at 21:25
  • 2
    No, we mean what is the value contained in the val reflect.Value? The error is that you have an unaddressable value, you cannot make that addressable after the fact. Commented Apr 23, 2021 at 21:26
  • 1
    If it is just string and not *string, I think that would be the source of your problem. Commented Apr 23, 2021 at 21:26
  • 2
    If you provide a reference to the library in question then we can provide a more specific answer (by looking at the source code). In general, if the value given to the reflect.Value was not a pointer to begin with, there's no meaningful way to turn it into a pointer, because all association with the original "real" value has been lost. (also btw try val.Type().String()) Commented Apr 23, 2021 at 21:32

2 Answers 2

1

I may don't have the complete code, but something like this works:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    s := "test"
    value := reflect.ValueOf(&s)
    ref := reflect.Indirect(value)
    ref.Set(reflect.ValueOf("test1"))
    fmt.Printf(s)
}
Sign up to request clarification or add additional context in comments.

Comments

-1

I saw something like this, using code from the last answerer.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    s := "test"
    ref := reflect.ValueOf(&s).Elem()
    ref.Set(reflect.ValueOf("test1"))
    fmt.Printf(s)
}

1 Comment

You can add more information about how this can help. Also, you can explain the differences between the code of the other answer and yours in order to help the community.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.