【发布时间】: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 = ""
显然其中一些是愚蠢的,但我没有看到尝试的危害。
我也尝试过使用reflect 和SetString:
reflect.ValueOf(t.value).SetString("")
这会导致编译错误
panic: reflect: reflect.Value.SetString 使用不可寻址的值
我假设这是因为 Go 中的字符串是不可变的?
【问题讨论】: