英文:
Set nil string pointer to empty string
问题
如何将类型中的字符串指针的引用值设置为空字符串?
考虑以下示例:
package main
import (
"fmt"
)
type Test struct {
value *string
}
func main() {
t := Test{nil}
if t.value == nil {
// 我想在这里将指针的值设置为空字符串
}
fmt.Println(t.value)
}
我尝试了所有组合的&
和*
运算符,但都没有成功:
t.value = &""
t.value = *""
&t.value = ""
*t.value = ""
显然,其中一些是愚蠢的,但我认为尝试一下也没有什么坏处。
我还尝试使用reflect
和SetString
:
reflect.ValueOf(t.value).SetString("")
但是这会导致编译错误
panic: reflect: reflect.Value.SetString using unaddressable value
我猜这是因为Go中的字符串是不可变的?
英文:
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 = ""
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("")
and this gives a compilation error
> panic: reflect: reflect.Value.SetString using unaddressable value
I'm assuming that's because strings in Go are immutable?
答案1
得分: 26
字符串字面量是不可寻址的。
获取包含空字符串的变量的地址:
s := ""
t.value = &s
或者使用new:
t.value = new(string)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论