将空字符串指针设置为空字符串。

huangapple go评论147阅读模式
英文:

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

显然,其中一些是愚蠢的,但我认为尝试一下也没有什么坏处。
我还尝试使用reflectSetString

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)

huangapple
  • 本文由 发表于 2017年6月5日 07:28:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/44359812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定