如何将类型中字符串指针的引用值设置为空字符串?
考虑这个例子:
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)
}
我已经尝试了所有组合&
and *
运算符无济于事:
t.value = &""
t.value = *""
&t.value = ""
*t.value = ""
显然其中一些是愚蠢的,但我没有看到尝试有什么坏处。
我也尝试过使用reflect
and SetString
:
reflect.ValueOf(t.value).SetString("")
这会产生编译错误
恐慌:反射:reflect.Value.SetString 使用不可寻址的值
我假设这是因为 Go 中的字符串是不可变的?
字符串文字不是可寻址的 https://golang.org/ref/spec#Address_operators.
获取包含空字符串的变量的地址:
s := ""
t.value = &s
或使用新的:
t.value = new(string)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)