将nil字符串指针设置为空字符串 [英] Set nil string pointer to empty string
本文介绍了将nil字符串指针设置为空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将类型中的字符串指针的引用值设置为空字符串? 考虑以下示例:
How do I set the referenced value of a string pointer in a type to the empty string? Consider this example:
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)
}
我尝试了&
和*
运算符的所有组合都无济于事:
I've tried all combinations of the &
and *
operators to no avail:
t.value = &""
t.value = *""
&t.value = ""
*t.value = ""
其中一些显然很傻,但是我没有发现尝试的危害.
我也尝试使用reflect
和SetString
:
Obviously some of those are silly, but I didn't see the harm in trying.
I also tried using reflect
and SetString
:
reflect.ValueOf(t.value).SetString("")
这会导致编译错误
恐慌:反映:使用无法寻址的值reflect.Value.SetString
panic: reflect: reflect.Value.SetString using unaddressable value
我假设这是因为Go中的字符串是不可变的?
I'm assuming that's because strings in Go are immutable?
推荐答案
字符串文字不是可寻址.
获取包含空字符串的变量的地址:
Take the address of variable containing the empty string:
s := ""
t.value = &s
或使用新的:
t.value = new(string)
这篇关于将nil字符串指针设置为空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文