Golang:将零字符串指针设置为空字符串
问题描述:
如何将类型中的字符串指针的引用值设置为空字符串? 考虑这个例子:Golang:将零字符串指针设置为空字符串
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("")
,这给编译错误
恐慌:反映:使用不可寻址值
我假设reflect.Value.SetString那是因为Go中的字符串是不可变的?