将nil字符串指针设置为空字符串

10

如何将类型中字符串指针的引用值设置为空字符串? 考虑以下示例:

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)
}

我已尝试了所有的 &* 运算符组合,但都没有成功:

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

显然,其中一些是愚蠢的,但我认为尝试一下也没有什么害处。 我还尝试使用reflectSetString

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

这会导致编译错误。

恐慌: 反射: reflect.Value.SetString 使用不可寻址的值

我猜这是因为 Go 中的字符串是不可变的?

1个回答

26

字符串字面量不可寻址。

获取包含空字符串的变量的地址:

s := ""
t.value = &s

或者使用新的:
t.value = new(string)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接