有没有一种惯用的Go语言方法来打印字符串指针的内容或nil值?

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

Is there an idiomatic go way to print string pointer contents or nil?

问题

我有一个字符串指针,可能为空,我想要打印出字符串的内容(如果存在),或者如果指针为空的话,指示指针为空。有没有一种聪明的方法可以做到这一点,而不需要使用 if 检查或临时变量(最好是一行代码)?

目前我正在使用类似这样的代码:

if p == nil {
    fmt.Print(p)
} else {
    fmt.Print(*p)
}

但是当有其他格式和其他变量打印在该值之前和/或之后时,这种方法特别笨拙和冗长。

英文:

I have a string pointer that may or may not be nil, and I want to print out either the contents of the string if contents exist, or indicate that the pointer is nil if it is nil. Is there a clever way to do this that doesn't involve either an if check or a temporary variable (preferably a single line)?

Right now I'm using something like this:

if p == nil {
    fmt.Print(p)
} else {
    fmt.Print(*p)
}

But this is particularly awkward and verbose when there is other formatting and other variables that are intended to be printed before and/or after that value.

答案1

得分: 6

你可以这样做:

func main() {
    var hello SmartString = "hello"

    p := &hello
    p.Print()
    p = nil
    p.Print()

}

type SmartString string

func (p *SmartString) Print() {
    if p == nil {
        fmt.Println(p)
    } else {
        fmt.Println(*p)
    }
}

无论这是否是一个好主意,都取决于你。

你甚至可以使用String接口使其与fmt.Println一起使用。

func main() {
    var hello SmartString = "hello"

    p := &hello
    fmt.Println(p)
    p = nil
    fmt.Println(p)

}

type SmartString string

func (p *SmartString) String() string {
    if p == nil {
        return "<nil>"
    }
    return string(*p)
}
英文:

You could do something like this:

func main() {
	var hello SmartString = &quot;hello&quot;

	p := &amp;hello
	p.Print()
	p = nil
	p.Print()

}

type SmartString string

func (p *SmartString) Print() {
	if p == nil {
		fmt.Println(p)
	} else {
		fmt.Println(*p)
	}
}

Whether it's a good idea or not is up to you.

You can even use the String interface to make it work with fmt.Println

func main() {
	var hello SmartString = &quot;hello&quot;

	p := &amp;hello
	fmt.Println(p)
	p = nil
	fmt.Println(p)

}

type SmartString string

func (p *SmartString) String() string {
	if p == nil {
		return &quot;&lt;nil&gt;&quot;
	}
	return string(*p)
}

huangapple
  • 本文由 发表于 2016年12月21日 23:42:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/41266630.html
匿名

发表评论

匿名网友

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

确定