2017-06-04 254 views
1

如何将类型中的字符串指针的引用值设置为空字符串? 考虑这个例子:Golang:将零字符串指针设置为空字符串

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 = "" 

显然他们有些是愚蠢的,但我没有看到危害在尝试。 我也使用reflectSetString尝试:

reflect.ValueOf(t.value).SetString("") 

,这给编译错误

恐慌:反映:使用不可寻址值

我假设reflect.Value.SetString那是因为Go中的字符串是不可变的?

回答

4

字符串文字不是addressable

以可变的包含空字符串的地址:

s := "" 
t.value = &s 

,或者使用新的:

t.value = new(string)