如何将类型中字符串指针的引用值设置为空字符串? 考虑这个例子:
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("")
这会产生编译错误
恐慌:反映:使用不可追踪的值反映.Value.SetString
我假设那是因为Go中的字符串是不可变的吗?
答案 0 :(得分:8)
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)