【问题标题】:Set nil string pointer to empty string将 nil 字符串指针设置为空字符串
【发布时间】:2017-11-05 16:30:49
【问题描述】:

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

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("")

这会导致编译错误

panic: reflect: reflect.Value.SetString 使用不可寻址的值

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

【问题讨论】:

    标签: string pointers go


    【解决方案1】:

    字符串文字不是addressable

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

    s := ""
    t.value = &s
    

    或使用新的:

    t.value = new(string)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-11
      • 2015-10-28
      • 2016-01-31
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多