10

How do I set the referenced value of a string pointer in a type to the empty string? Consider this example:

package main

import (
    "fmt"
)

type Test struct {
    value *string
}

func main() {
    t := Test{nil}
    if t.value == nil {
        // I want to set the pointer's value to the empty string here
    }

    fmt.Println(t.value)
}

I've tried all combinations of the & and * operators to no avail:

t.value = &""
t.value = *""
&t.value = ""
*t.value = ""

Obviously some of those are silly, but I didn't see the harm in trying. I also tried using reflect and SetString:

reflect.ValueOf(t.value).SetString("")

and this gives a compilation error

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

I'm assuming that's because strings in Go are immutable?

1 Answer 1

27

String literals are not addressable.

Take the address of variable containing the empty string:

s := ""
t.value = &s

or use new:

t.value = new(string)
Sign up to request clarification or add additional context in comments.

Comments

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.