简体   繁体   中英

Set nil string pointer to empty string

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM