Jim*_*y P 3 string pointers go
如何将类型中字符串指针的引用值设置为空字符串?考虑这个例子:
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)
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了&
和*
运营商的所有组合无济于事:
t.value = &""
t.value = *""
&t.value = ""
*t.value = ""
Run Code Online (Sandbox Code Playgroud)
显然其中一些是愚蠢的,但我没有看到尝试的伤害.我也尝试过使用reflect
和SetString
:
reflect.ValueOf(t.value).SetString("")
Run Code Online (Sandbox Code Playgroud)
这给出了编译错误
恐慌:反映:reflect.Value.SetString使用无法寻址的值
我假设那是因为Go中的字符串是不可变的?
Cer*_*món 12
字符串文字不可寻址.
获取包含空字符串的变量的地址:
s := ""
t.value = &s
Run Code Online (Sandbox Code Playgroud)
或使用新的:
t.value = new(string)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4715 次 |
最近记录: |